简体   繁体   English

如何使用一个 ajax 调用执行两个操作 - WordPress

[英]How to execute two actions with one ajax call - WordPress

I have a section for "tours" in my page.我的页面中有一个“旅游”部分。

The tours have 2 filters (select inputs).游览有 2 个过滤器(选择输入)。 "destino" and "duracion" (location and duration) “destino”和“durasion”(位置和持续时间)

So far I made one of the filter work with ajax, and update the "#result" id with the new tours once you select a "destino".到目前为止,我使用 ajax 制作了一个过滤器,并在您将 select 设置为“destino”时使用新的游览更新“#result”ID。

But i also want to update the "duracion" select with the new options (based on the destino selected).但我也想用新选项(基于选择的 destino)更新“durasion”select。

Problem is, i have no idea how to execute two actions and have the response on two different places.问题是,我不知道如何执行两个动作并在两个不同的地方做出响应。

Html part: (here I have both actions, its only executing the last one) Html 部分:(这里我有两个动作,它只执行最后一个)

<form class="filtros righter" action="**********/wp-admin/admin-ajax.php" method="POST" id="filtro">
<input type="hidden" name="action" value="filtertoursajax">
<input type="hidden" name="action" value="filterduracionajax">
<input type="hidden" name="filtrodestino" value="salar-de-uyuni">

        <div class="select-holder">
        <label class="">Categoría</label>   
            <select name="categoriafilter" id="categoriafilter">
                <option disabled="" selected="" value="0">&nbsp;</option>
                <option value="0">Todas las categorías</option>
                <option value="11">Clásicos</option>
                <option value="33">Elite</option>
            </select>
        </div>
        <div class="select-holder"> 
        <label>Duración del viaje</label>
            <select name="duracionfilter" id="resultselect">
                <option disabled="" selected="" value="0">&nbsp;</option>
                <option value="0">Todas las duraciones</option>
            </select>
        </div>
</form>

Js part: Js部分:

<script>
jQuery(function myFunction(){
$('#filtro').change(function(){
    var filter = $('#filtro');
    $.ajax({
        url:filter.attr('action'),
        data:filter.serialize(), // form data
        type:filter.attr('method'), // POST
        beforeSend:function(xhr, data){
            filter.find('button').text('Processing...'); // changing the button label
        },
        success:function(data){
            filter.find('button').text('Apply filter'); // changing the button label back
            $('#response').html(data); // insert data
            console.log(data);
        },
        error: function(req, err){ console.log(err);
        }
    });
    return false;
});

}); });

PHP action 1: PHP 动作 1:

add_action('wp_ajax_filtertoursajax', 'filtertoursajax');
add_action('wp_ajax_nopriv_filtertoursajax', 'filtertoursajax');


function filtertoursajax(){

    $args = array(
        'post_type' => 'tours',
        'orderby' => 'menu_order',
        'order' => 'ASC',
        'post_per_page' => -1,
    );

    if( isset($_POST['filtrodestino']) && $_POST['filtrodestino'] ) {

        // for taxonomies / categoria
            if( isset( $_POST['filtrodestino'] ) ) {
                $args['tax_query'][] = 
                    array(
                        'taxonomy' => 'destino',
                        'field' => 'slug',
                        'terms' => $_POST['filtrodestino']
                    
                );
            }           
    }


    if( isset($_POST['categoriafilter']) && $_POST['categoriafilter'] ) {

        // for taxonomies / categoria
                $args['tax_query'][] = 
                    array(
                        'taxonomy' => 'categoria',
                        'field' => 'id',
                        'terms' => $_POST['categoriafilter']
                    
                );
    }

 
    $query = new WP_Query( $args );
    if( $query->have_posts() ) :
        print_r($args);
        while( $query->have_posts() ): $query->the_post();

            $postid = $query->post->ID;

            $taxonomy = 'destino';  
            $terms = get_the_terms( get_the_ID(), $taxonomy );
                          
            if ( $terms && ! is_wp_error( $terms ) ) : 
             
                $term_links = array();
             
                foreach ( $terms as $term ) {
                    $term_links[] = '<a href="' . esc_attr( get_term_link( $term->slug, $taxonomy ) ) . '">' . __( $term->name ) . '</a>';
                }
                                     
                $all_terms = join( ', ', $term_links );
     
                $destinos = '<span class="terms-' . esc_attr( $term->slug ) . '">' . __( $all_terms ) . '</span>';
     
            endif;

            ?>
            <div class="box">
                <div class="box__image flexer">
                    <?php echo wp_get_attachment_image( get_field( "foto_portada", $postid ), array('276', '180'), "", array( "class" => "img-responsive" ) );  ?>
                </div>
                <div class="box__content pz-1">
                    <span class="placeholder mb-1"><?php echo $destinos; ?></span>
                    <h6 class="long-title mb-2"><?php echo $query->post->post_title; ?></h6>
                    <div class="icon-btn"><?php $path = get_template_directory_uri().'/images/plane-icon.svg'; echo file_get_contents($path); ?>Duración: <?php echo get_field( "duracion_texto", $postid ); ?></div>
                </div>
                <a href="<?php echo the_permalink(); ?>" class="text-btn pl-1">Ver ficha<?php $path = get_template_directory_uri().'/images/arrow-btn.svg'; echo file_get_contents($path); ?></a>
            </div>

        <?php endwhile;
        wp_reset_postdata();
    else:
        echo 'Sin resultados';
        print_r($args);
    endif;
 
    die();

}

PHP action 2: PHP 动作 2:

add_action('wp_ajax_filterduracionajax', 'filterduracionajax'); // 
add_action('wp_ajax_nopriv_filterduracionajax', 'filterduracionajax');

function filterduracionajax(){

        if( $args = array(
                        'posts_per_page'    => -1,
                        'hide_empty' => 1,
                        'post_type'     => 'tours',
                        'meta_key'      => 'dias',
                        'orderby'           => 'meta_value',
                        'order'             => 'ASC',
                    ) ) :


        // create $args['tax_query'] array if one of the following fields is filled
    if( isset($_POST['filtrodestino']) && $_POST['filtrodestino'] ) {

        // for taxonomies / categoria
            if( isset( $_POST['filtrodestino'] ) ) {
                $args['tax_query'][] = 
                    array(
                        'taxonomy' => 'destino',
                        'field' => 'slug',
                        'terms' => $_POST['filtrodestino']
                    
                );
            }           
    }


// create $args['tax_query'] array if one of the following fields is filled
    if( isset($_POST['categoriafilter']) && $_POST['categoriafilter'] ) {

        // for taxonomies / categoria
                $args['tax_query'][] = 
                    array(
                        'taxonomy' => 'categoria',
                        'field' => 'id',
                        'terms' => $_POST['categoriafilter']
                    
                );
    }


        // query
        $the_query = new WP_Query( $args );
        if( $the_query->have_posts() ): ?>

        <div class="select-holder"> 
        <label>Duración del viaje</label>
        <select name="duracionfilter" id="resultselect">
        <option disabled="" selected="" value="0">&nbsp;</option>
        <option value="0" >Todas las duraciones</option>
            
            <?php $unique_dias = array();

            while( $the_query->have_posts() ) : $the_query->the_post(); ?>
                <?php $dias = get_field('dias');

                if( ! in_array( $dias, $unique_dias ) ) :
                            $unique_dias[] = $dias; ?>
                <?php endif;
            endwhile;
            natsort($unique_dias);
            foreach ( $unique_dias as $duraciones ) :
                    echo '<option value="'.$duraciones.'">'.$duraciones.'</option>';
            endforeach;

            ?>

        </select></div>
        <?php endif;

     endif;

     die();

}

Im very new with Ajax, this code is made by pieces of tutorials i found.我对 Ajax 很陌生,这段代码是由我找到的一些教程制作的。 The code is mostly made following this tutorial: https://rudrastyh.com/wordpress/ajax-post-filters.html I just need both php actions to execute on "form" change and update the "tours" on #response div and also update the select input with #resultselect id. The code is mostly made following this tutorial: https://rudrastyh.com/wordpress/ajax-post-filters.html I just need both php actions to execute on "form" change and update the "tours" on #response div and还使用#resultselect id 更新 select 输入。

Thanks!谢谢!


Thanks to @lewis4you I'm able to get the data on the 2 divs at the same time.感谢@lewis4you,我能够同时获取 2 个 div 上的数据。 But i fail to understand how to execute both actions at the same time, but with different actions from functions.php但我不明白如何同时执行这两个动作,但功能不同。php

This这个

add_action('wp_ajax_filterduracionajax', 'filterduracionajax'); // 
add_action('wp_ajax_nopriv_filterduracionajax', 'filterduracionajax');

has to return data to #resultselect必须将数据返回到#resultselect

and

add_action('wp_ajax_filtertoursajax', 'filtertoursajax'); 
add_action('wp_ajax_nopriv_filtertoursajax', 'filtertoursajax');

has to return data to #response div必须将数据返回到#response div

My main problem is that i dont know how to select the action i want to execute in我的主要问题是我不知道如何 select 我要执行的操作

$.ajax({
          url:filter.attr('action'),
          data:filter.serialize(), // form data
          type:filter.attr('method'), // POST

I didn't read the question fully but I think you want something like this:我没有完全阅读这个问题,但我认为你想要这样的东西:

$('#filtro').change(function() {
    var filter = $('#filtro');
    ajax1(filter);
    ajax2(filter);
});


function ajax1(filter) {
 $.ajax({
    url:filter.attr('action'),
    data:filter.serialize(), // form data
    // ... further code
}

function ajax2(filter) {
 $.ajax({
    url:filter.attr('action'),
    data:filter.serialize(), // form data
    // ... further code
}

The scenario where you send the data to the same controller from one $.ajax call:您通过一次 $.ajax 调用将数据发送到同一 controller 的场景:

$('#filtro').change(function() {
    var filter = $('#filtro');
    ajax1(filter);
});

in controller you have to store the data into array with keys so you can access it later in ajax success() function在 controller 中,您必须使用键将数据存储到数组中,以便稍后在 ajax success() function 中访问它

public function someFunction($dataFromAjax) {

    // do something with $dataFromAjax

    $dataForDivs = [
        'div1' => 'some data',
        'div2' => 'some data2'
    ];

    return $dataForDivs;
}

then in your $ajax in success:function(data) you can access that data with然后在你的 $ajax 中success:function(data)你可以访问该数据

success:function(data) {
    let div1Data = data.responseJSON.div1;
    let div2Data = data.responseJSON.div2;
    filter.find('button').text(div1Data); // changing the button label back
    $('#response').html(div2Data); // insert data
    console.log(div1Data, div2Data);
},

Have you thought of using JS's Fetch API instead of jQuery's Ajax?有没有想过用 JS 的 Fetch API 代替 jQuery 的 Ajax? Fetch returns a promise then it can execute a chain of.then() blocks where you can put another fetch() to your PHP url. Fetch 返回一个 promise 然后它可以执行一系列.then() 块,您可以在其中将另一个 fetch() 放入 PHP url。

See an example here:在此处查看示例:

using a fetch inside another fetch in javascript 在 javascript 中的另一个 fetch 中使用 fetch

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM