Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display the progress of a server script in jQuery?

Tags:

jquery

ajax

With this code I can show an animated gif while the server script is running:

function calculateTotals() {
    $('#results').load('getResults.php', null, showStatusFinished);
    showLoadStatus();
}

function showLoadStatus() {
    $('#status').html('');
}


function showStatusFinished() {
    $('#status').html('Finished.');
}

However, I would like to display a status of how far along the script is, e.g. "Processing line 342 of 20000..." and have it count up until it is finished.

How can I do that? I can make a server-script which constantly contains the updated information but where do I put the command to read this, say, every second?

like image 746
Edward Tanguay Avatar asked Sep 16 '08 12:09

Edward Tanguay


2 Answers

After reading your comments to Andrew's answer.

You would read the status like this:

function getStatus() {
    $.getJSON("/status.php",{"session":0, "requestID":12345}, 
    function(data) { //data is the returned JSON object from the server {name:"value"}
          setStatus(data.status);
          window.setTimeout("getStatus()",intervalInMS)
    });
}

Using this method you can open several simultaneous XHR request on the server.

all your status.php as to output is :

{"status":"We are done row 1040/45983459"}

You can however output as many information you want in the response and to process it accordingly (feeding a progress bar for example or performing an animation..)

For more information on $.getJSON see http://docs.jquery.com/Ajax/jQuery.getJSON

like image 73
matdumsa Avatar answered Oct 10 '22 18:10

matdumsa


I'm not down with the specifics for jQuery, but a general answer that doesn't involve polling wold be: Use a variation of the forever frame technique. Basically, create a hidden iframe, and set the src of it to be 'getresults.php'. Inside getresults you "stream" back script blocks, which are calls to a javascrpt function in the parent document that actually updates the progress. Here's an example that shows the basic idea behind a forever frame. (I wouldn't recommend using his actual JS or HTML though, it's reasonably average)

like image 28
Dan F Avatar answered Oct 10 '22 17:10

Dan F