Deano Deano - 1 year ago 55
Javascript Question

jQuery to check status of a asynchronous task

I'm interacting with a web service, and I'm using ajax method with jQuery.

To interact web service I have a php file " process.php" that produces 3 different values based on the request status, ( 0 ) for pending process, (1) for success and (2) for failure.

Question: how can I use jQuery to continue checking job status until it from 0 to either 1 or 2?

I'm confused about how I can get this done.

Any ideas about who I can go about doing this would be helpful :)

Thanks for your help

Answer Source

You should poll process.php continuously to keep checking its resposnse

Something like this:

function getProcessStatus() {
    $.get('process.php', function(response) {
        //Do something with the response, like storing it into a variable
        if(response.status == 0) {
            setTimeout(getProcessStatus, 1000);

This does a first GET request and then, upon success, schedules it to be done again after one second if the process is still pending.

Also note that you could also use some more complicated solutions like websockets in order to have the status of the process updated in realtime, but this solution is in my opinion simple enough if you don't have any realtime requirements.