Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat jQuery JSON request until condition is met

Tags:

json

jquery

Greetings,

I am trying to repeat a JSON request in jQuery to check the status of a video encoding job until it is completed. "Processing" would be displayed until the job is finished, at which point the video will be displayed.

Would a loop, checking every x seconds to see if "status" equals "finished," be the best solution for this? If so, how would I break free from this loop when the job is finished?

The JSON response while the job is in progress will be nothing more than "processing," when it is finished it will contain things such as the job ID, width, and height.

Any help would be appreciated, thanks!

UPDATE

Here's my final solution thanks to Felix:

var checkStatus = function() {
    $.getJSON('json-data.php', function(data) {
    if (data.status != 'finished') {
          setTimeout(checkStatus, 2000);
    } else {
//Sample code to run when finished
$("#statusText").text("Job Complete");
           $("#dimensions").text(data.width + 'x' + data.height);
        }
     });
    };
checkStatus();
like image 363
NightMICU Avatar asked Feb 15 '11 01:02

NightMICU


2 Answers

A loop won't work as the Ajax request is asynchronous.

One way would be to make same kind of recursive call and trigger the Ajax function again from the success callback (maybe after some timeout), if the condition is not met.

Something like (pseudo code):

function check_condition() {
    $.getJSON(<url>, function(result) {
        if(!result.finished) {
            setTimeout(check_condition, 2000);
        }
        // do something else
    } 
}
like image 66
Felix Kling Avatar answered Nov 16 '22 03:11

Felix Kling


var checkStatusInterval = 30 * 10000; // 30 seconds
var checkStatusFunc = function(){
  $.getJSON('getMovieStatus', function(data){
    if (data.Incompleted){ // or however you check
      checkStatusTimer = setTimeout(checkStatusFunc, checkStatusInterval);
    }
  });
};
var checkStatusTimer = setTimeout(checkStatusFunc,checkStatusInterval );

To stop:

<input type="button" id="stopchecking" value="Stop Checking..." />
$('#stopchecking').click(function(e){
  clearTimeout(checkStatusTimer);
});
like image 34
Brad Christie Avatar answered Nov 16 '22 02:11

Brad Christie