javascript – WordPress Ajax send response on every iteration of a loop

Question

I am trying to get an ajax request to update the response as it goes through a loop, similar to a progress bar.

A bit of background on this snippet. Here is the JS Ajax request:

// ------------initiate ajax call to generate database entries------------
var ajax_data = {};
ajax_data.action = 'database_generate';
// ------------run ajax call and return response------------
jQuery.ajax({
  method: 'post',
  url: '/wp-admin/admin-ajax.php',
  data: ajax_data,
  success: function(response){
    response_container.innerText = response;
  }
});

The javascript is pretty straightforward “success” response. I suspect that this may be part of the issue as to why it wont return until the loop finishes. I don’t know how to call it differently to update.

Here is the PHP Snippet:

// ------------loop through grouped CSV data------------
foreach ($return_arrary as $current_post) {
  // ------------check if current state exists in database------------
  if (!$post_exists($current_post['State'])) {
    // ------------create post data------------
    $post_array = array(
      'post_title' => $current_post['State'],
      'post_type' => 'jed_map_states',
      'post_status' => 'publish'
    );
    // ------------insert post into database------------
    wp_insert_post($post_array);
    $counter++;
  }
}
echo $counter." States added to database.";

The php is needs a tad more context. $return_array is a list of state names that are grabbed from a csv file. $post_exists is $wpdb call to check if a post with the same title has been created. $counter is initialized earlier in the script. If I place the echo inside of the foreach loop it only sends a huge response of each iteration after the loop finishes ie:

0 States Added
1 States Added
2 States Added
…etc etc

I suspect that it takes a bit since it has to make the $wpdb call every time on loop. I would be great if there was a real-time update as its working.

Any help would be greatly appreciated!

0
sallycakes 2 weeks 2022-11-19T17:57:03-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse