plugin development - Ajax is not working in a loop

admin2025-06-03  2

I am trying to show data associated with selected categories by using ajax. Its working only for the last term selected, not for all the selected terms. Any help would be highly appreciated.

var selected_cat = $('#my-categorychecklist input:checked').map(function() {
    return this.value
}).get();

   $(document).ready( function () {
         var getid = $('#my-categorychecklist input:checked').last().val();
         var matchid = $('#my-categorychecklist input:checked').last().val();

         $('#section').html('<div class="spinner"></div>');
         var data = {
             'action': 'fields_selected',
             'post_id': $('#fields-list-selected').data('post_id'),
             'term_id': selected_cat
         };

             $.post(ajaxurl, data, function (response) {
                     if(response != 0) {
                         $('.block'+getid).html(response);
                         $('[data-toggle="tooltip"]').tooltip();
                     } else {
                         $('.block'+getid).html(" ");
                         $('[data-toggle="tooltip"]').tooltip();
                     }
             });

     });///////PHP AJAX CALLBACK START
    $args = null;
    if (!empty($term_ids)){ //terms ids
        foreach($term_ids as $term_id){
            $args = array(
                'post_type'      => 'my_post',
                'posts_per_page' => -1,
                'meta_query'    => array(
                    'relation' => 'AND',
                    array(
                        'key'       => 'category',
                        'value'     => $term_id,
                        'compare'   => 'EXISTS',
                    ),
                    array(
                        'key'       => 'associate',
                        'value'     => 'categories',
                        'compare'   => 'LIKE',
                    )
                )
            );
            $query = new WP_Query( $args );
            if ($query->have_posts()){

                // Start the Loop
                global $post;
                // Process output
                ob_start();

                include MY_TEMPLATES_DIR . 'custom-field.php';
                wp_reset_postdata(); // Restore global post data stomped by the_post()
                $output = ob_get_clean();

                print $output;

                if( $ajax ) {
                    wp_die();
                }
            } else{
                // Process empty output
                ob_start();
                ?>
                <?php
                $output = ob_get_clean();
                print $output;
                //print "No data found !";
            }
        }
    }/*AJAX CALLBACK END*/if ($term_id_selected) {
        foreach ($term_id_selected as $single_term){
        ?>
        <div id="fields-list-selected" data-post_id="<?php echo $post_ID; ?>">
            <?php
            do_action('wp_ajax_fields_selected', $post_ID, $single_term); ?>
        </div>
        <?php
    }}

I am trying to show data associated with selected categories by using ajax. Its working only for the last term selected, not for all the selected terms. Any help would be highly appreciated.

var selected_cat = $('#my-categorychecklist input:checked').map(function() {
    return this.value
}).get();

   $(document).ready( function () {
         var getid = $('#my-categorychecklist input:checked').last().val();
         var matchid = $('#my-categorychecklist input:checked').last().val();

         $('#section').html('<div class="spinner"></div>');
         var data = {
             'action': 'fields_selected',
             'post_id': $('#fields-list-selected').data('post_id'),
             'term_id': selected_cat
         };

             $.post(ajaxurl, data, function (response) {
                     if(response != 0) {
                         $('.block'+getid).html(response);
                         $('[data-toggle="tooltip"]').tooltip();
                     } else {
                         $('.block'+getid).html(" ");
                         $('[data-toggle="tooltip"]').tooltip();
                     }
             });

     });///////PHP AJAX CALLBACK START
    $args = null;
    if (!empty($term_ids)){ //terms ids
        foreach($term_ids as $term_id){
            $args = array(
                'post_type'      => 'my_post',
                'posts_per_page' => -1,
                'meta_query'    => array(
                    'relation' => 'AND',
                    array(
                        'key'       => 'category',
                        'value'     => $term_id,
                        'compare'   => 'EXISTS',
                    ),
                    array(
                        'key'       => 'associate',
                        'value'     => 'categories',
                        'compare'   => 'LIKE',
                    )
                )
            );
            $query = new WP_Query( $args );
            if ($query->have_posts()){

                // Start the Loop
                global $post;
                // Process output
                ob_start();

                include MY_TEMPLATES_DIR . 'custom-field.php';
                wp_reset_postdata(); // Restore global post data stomped by the_post()
                $output = ob_get_clean();

                print $output;

                if( $ajax ) {
                    wp_die();
                }
            } else{
                // Process empty output
                ob_start();
                ?>
                <?php
                $output = ob_get_clean();
                print $output;
                //print "No data found !";
            }
        }
    }/*AJAX CALLBACK END*/if ($term_id_selected) {
        foreach ($term_id_selected as $single_term){
        ?>
        <div id="fields-list-selected" data-post_id="<?php echo $post_ID; ?>">
            <?php
            do_action('wp_ajax_fields_selected', $post_ID, $single_term); ?>
        </div>
        <?php
    }}
Share Improve this question edited Feb 10, 2019 at 11:00 Rafiq asked Feb 10, 2019 at 9:00 RafiqRafiq 1001 gold badge1 silver badge9 bronze badges 2
  • Can you please add the code of your PHP function that is handling the request? – Boris Kuzmanov Commented Feb 10, 2019 at 10:20
  • @BorisKuzmanov --I have edited my code. Please check. – Rafiq Commented Feb 10, 2019 at 11:01
Add a comment  | 

1 Answer 1

Reset to default 2

Your code has

 var getid = $('#my-categorychecklist input:checked').last().val();

see the .last(), that's why you're only getting the last item Also, why do you have the same thing in getid and matchid?

You need to store the selected categories in an array and loop through them, try something like:

var selected_cats = $('#my-categorychecklist input:checked').map(function() {
    return this.value
})

(without the .get()) then loop through them with

    selected_cats.forEach(function(element) {
        console.log(element)
      //make sure element has what you're expecting then do you something on element
}

Try doing console.log() on each variable and see in your console, if the the variables have the result you're expecting. Make sure that selected_cats has an array of the selected categories

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748921778a314839.html

最新回复(0)