$conf, $runtime; function_exists('chdir') AND chdir(APP_PATH); $r = 'mysql' == $conf['cache']['type'] ? website_set('runtime', $runtime) : cache_set('runtime', $runtime); } function runtime_truncate() { global $conf; 'mysql' == $conf['cache']['type'] ? website_set('runtime', '') : cache_delete('runtime'); } register_shutdown_function('runtime_save'); ?>plugin development - Ajax is not working in a loop|Programmer puzzle solving
最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

plugin development - Ajax is not working in a loop

matteradmin10PV0评论

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

Post a comment

comment list (0)

  1. No comments so far