Search code examples
phpjqueryajaxpromiseprogress

Check and display a PHP function's progress with AJAX


I want to display the progress of a PHP function in my webbrowser. One solution would be to put the progress in the database and poll for it while the AJAX function waits for a response, but I was wondering if there's a better and cleaner way of doing this.

I've looked into this plugin which adds a progress promise to the AJAX call in jQuery, but it only seems to support uploads and downloads.

To illustrate what I would like to achieve, my AJAX call looks something like this:

$.ajax({
    type: 'POST',
    dataType:'json',
    url: ajaxUrl,
    data: someData
}).progress(function(response) {

    // Do something with progress messages

}).done(function(response) {

    // Process complete
});

Lets say it calls this function in PHP:

public function heavy_lifting() {

    echo json_encode( array( 'progress', 'Starting!') );

    sleep(1);

    echo json_encode( array( 'progress', 'Pfew') );

    sleep(1);

    echo json_encode( array( 'progress', 'Almost done!') );

    sleep(1);

    // Done!
    echo json_encode( array( 'done', 'Process completed!') );
    die();

}

What's the best way to do something like this?


Solution

  • A better approach will be to use Websockets (Ratchet WebSockets for PHP)

    Create a Websocket server in PHP, then register that Websocket on webpage using javascript

    // Create WebSocket connection.
    const socket = new WebSocket('ws://localhost:8080');
    
    // Connection opened
    socket.addEventListener('open', function (event) {
        socket.send('Hello Server!');
    });
    
    // Listen for messages
    socket.addEventListener('message', function (event) {
        console.log('Message from server', event.data);
    });
    

    Whenever there is a change in progress then push event from server which will be received by javascript message eventListener and perform your task after that.

    Websocket approach is better than polling.