2

I'm writing code in PHP that analyzes user input. I'm hoping to analyze it through a AJAX request using jquery. I'd like to provide real-time feedback to the user while I'm preforming the calculations. For example: "Uploading your input", "Analyzing", "Preparing final result" and so forth. How can I go abut doing this?

2 Answers2

1

You will have to have a different back-end script do the processing than the one you are sending your request to. Your original ajax request can store the user input to be analyzed, and another process check for new data to work on regularly and start working when it finds some. That background process can then record its progress, e.g. using a file or a database.

The subsequent ajax requests will check that progress file or database entry and display the progress to the user.

Another (more complicated) solution would be to use Comet to push information on the status from the server to the browser. There is a comet plugin for JQuery in the works, as described in StackOverflow question 136012.

Community
  • 1
  • 1
Brian Ramsay
  • 7,160
  • 8
  • 37
  • 52
1

Assuming you have a service located at /service-status.php that checked the status of the job and returned a string you could do something like this in a interval.

var intervalId;
intervalId = setInterval( function() {
   $.ajax({
       type: "POST",
       url: "/service-status.php",
       data: "jobid=" + id,
       success: function(msg){
         if (msg === 'Finished') {
           clearInterval( intervalId );
         }
         alert( "Status: " + msg );
       },
       error: function(XMLHttpRequest, textStatus, errorThrown) {
          alert("He's dead Jim"):
          clearInterval( intervalId );
       }

  })
}, 500);

This would poll your service every 500ms. It also assumes that you return 'Finished' when done. Adjust accordingly. I might put a counter in there too to clear the interval just in case so you don't DDOS your own server.

seth
  • 34,791
  • 7
  • 58
  • 57