user13286
user13286

Reputation: 3075

Keeping a live log while looping through PHP in an AJAX call

I am creating a Wordpress plugin to call an API and create new Wordpress posts for each object returned in the response. Here is the PHP for my function that loops over the API response to create new Wordpress posts:

add_action('wp_ajax_sync_posts', 'sync_posts_from_api' );
function sync_posts_from_api() {
    // MAKING API CALL HERE
    
    foreach ($data as $post) {
        $new_post = array(
            'post_type'     => 'post',
            'post_title'    => $post->title,
            'post_status'   => 'publish',
            'post_author'   => 1,
            'post_content'  => $post->description,
        );
        $wp_post = wp_insert_post($new_post);

        echo '<pre>Post ID ' . $wp_post->ID . ') has been created.</pre>';
    }
}

And then I have my Javascript like this:

jQuery(function($) {
    $('form').submit(function(e) {
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: ajaxurl,
            data: { 
                action: 'sync_posts'
            },
        }).done(function(response) {
            $('.log').html(response);
        });
    });
});

This works after the AJAX call is completely finished, but I am hoping to be able to append each echo to the .log container as it goes, instead of all at once when the call is finished. How would I go about making that change?

Upvotes: 0

Views: 110

Answers (1)

Enrico Dias
Enrico Dias

Reputation: 1487

You can only access the ajax request response after the request finishes. The proper way of accomplishing what you want is using web sockets.

In the old days we used to create an iframe loading with something like this:

foreach ($data as $post) {

    echo "
        <script>
            window.parent.postMessage({message: '".$post."'}, 'http://localhost/');
        </script>
    ";

    flush();
}

The browser executes the js in real time when loading the page and the js sends a message to the parent frame. You'll also need the proper js code on the parent frame to receive and process those posts. Even though this may still work, it's very sketchy and not recommended.

Upvotes: 1

Related Questions