I am seeking terminology or links to related questions for what I am trying to achieve here...
I use jquery ajax all the time with wordpress, but is it possible to send data back to my jquery ajax function midway through the running php function?
My goal is to create a front-end progress bar, showing the status of the running ajax php function tasks.
So I tried using wp_send_json_success()
within the ajax fired php function in each completed post loop output... but it seems wp_send_json_success()
returns rather than continues. So the js ajax success response only ever returns the first sent wp success response data...
$.ajax({
cache: false,
timeout: 300000, // 5 hours
url: admin_ajax_url,
type: 'GET',
data: {
action : 'test',
},
success: function (response) {
console.log(response);
}
});
<?php
class Test {
public function __construct() {
add_action('wp_ajax_nopriv_test', [$this, 'ajax_test'], 20);
add_action('wp_ajax_test', [$this, 'ajax_test'], 20);
}
public function ajax_test() {
$args = [
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => -1,
'order' => 'ASC',
'orderby' => 'ID',
];
$products = new WP_Query($args);
if($products->have_posts()) :
while($products->have_posts()): $products->the_post();
global $post;
// i want to send data back to my js ajax every time this is hit
// but wp_send_json_success returns first time it is hit (see my console.log below...)
wp_send_json_success([
$post->ID => true
]);
endwhile;
endif;
die();
}
}
new Test();
JS consoled log response for the above code...
wp_send_json_success()
returns (doesn't continue) and the response exits the first time it is hit in the php function.
Is it possible to send multiple intermittent data responses back to my jquery ajax function until the php function is complete (.done
)?
Any links to questions or terminology for me to work on a solution... (if this is possible with jquery ajax)... would be massively appreciated, thanks!
If it is not possible, what is the alternative?... To send a new ajax request for every task to be executed?... this sounds heavy, unreliable and illogical.
Thanks in advance for any advice!