Repeat AJAX GET Until a Specific Response is Met in jQuery

Posted on September 29, 2019 at 5:06 pm

Here is how to repeat an AJAX GET call until a specific response is met:

function repeated_ajax_check(url) {
    $.ajax
        ({
            type: 'GET',
            url: url,
            dataType: 'json',
            success: function(result) {
                if(result.success) { 
                    console.log("We finally met our response!");
                    console.log(result);
                    //Do something other here, for example:
                    //$('.result-message').html('RESPONSE MET!');
                    //$('.result-message').show();
                }else{
                    console.log("Response not yet met.");
                    console.log(result);
                    wait(1000);
                    repeated_ajax_check(url);
                }
            },
            error: function() {
                console.log("There was an error.");
                //Want to repeat AJAX call also in case of error? 
                //Then just uncomment the following two lines:
                //wait(1000);
                //repeated_ajax_check(url);
            }
    });
}

We use the following wait() function to wait 1 second between each AJAX call:

function wait(ms) { const start = performance.now(); while(performance.now() - start < ms); }

You can use the function like this:

repeated_ajax_check("https://api.ipify.org?format=json");

Receive updates via email

Other Posts

Updated Posts