0

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...

enter image description here


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!

joshmoto
  • 4,472
  • 1
  • 26
  • 45

1 Answers1

0

I do not think you can send a single request and recieve multiple responses, as you would if you were streaming the data. See this thread, jQuery read AJAX stream incrementally?.

For your use case, I think it would be better to recieve all of the post information in a single request, as this would avoid information being output to the DOM at different times, which might make it seem a bit clunky.

I would move the wp_send_json_success() function outside the post loop, so you get all the information from the query in a single response.

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()) :

        //Variable to store all the results from the query
        $response_data = [];

        while($products->have_posts()): $products->the_post();

            global $post;

            $response_data[] = [ $post->ID => true ];

        endwhile;

    endif;

    //Send response back to front end
    wp_send_json_reponse($reponse_data);      

    die();

}

You could change the number of posts that are output by including a the desired number of posts as post data, as seen below;

$.ajax({
cache: false,
timeout: 300000, // 5 hours
url: admin_ajax_url,
type: 'GET',
data: {
    action : 'test',
    posts_per_page : 3 //Maximum number of posts that can be returned 
},
success: function (response) {

    console.log(response);

}

});

And then implementing that data in the $args arrays with;

'posts_per_page'    => $_POST['posts_per_page'],

Edit: This link solved the OP's question.

  • Thank you for your answer and time, but I am asking if a php response can be sent back to my jquery ajax function more than once. So I can calculate a progress bar to show the progress status of the running ajax called php. If I run `wp_send_json_reponse()` after my loop, then progress data will show as 100% when `ajax_test` has finished... meaning my progress bar would start at 0% and finish at 100% in one hit (after however long the php takes to run). I want to send back ajax responses after each looped php post, so I can show progress via a progress bar in %. – joshmoto Nov 13 '21 at 04:27
  • I updated my question title as it may have be vague but i think my question is clear, please let me know if my question did not make sense. – joshmoto Nov 13 '21 at 04:48
  • 1
    Yes, I do not think that this is possible. I think that a single request receives a single response. I think that you are hoping to stream data via a socket, which is not possible via AJAX (https://stackoverflow.com/questions/7740646/jquery-read-ajax-stream-incrementally). I think that this thread might be the what you are looking for, https://stackoverflow.com/questions/6475238/multiple-response-ajax-request. – QuirkyGoodFriend Nov 13 '21 at 05:51
  • the last link is what I am looking for thanks very much for you help – joshmoto Nov 13 '21 at 18:04
  • @joshmoto could I get you to mark my answer as the correct answer? I have appended the link to the question. – QuirkyGoodFriend Aug 11 '22 at 00:56