Search code examples
javascriptjqueryajaxget

How to automatically rerun ajax call when xhr returns 503


In my app I'm using an AJAX get request to call an API configured using API Gateway in AWS. Sometimes when the API hasn't been called in awhile it will error out with a 503 because the server is trying to fire up again. I want to be able to automatically rerun the ajax call if it comes back with the 503 error because the server is trying to start up.

I'm not sure what to include in the error function. I tested it with an alert to say fail if the call returns a 503 error, but I'm not sure what to include to automatically rerun the call Any advice on how to achieve this is greatly appreciated! Thanks!

$(".apiGateway").on("click", function (e) {
        e.preventDefault();
       
            $.ajax({
                url: 'apiGatewayURL',
                method: 'GET',
                error: function (xhr) {
                   if (xhr.status === 503) {
                       alert('fail')
                   }
                }
            })
        

    })

Solution

  • Use $.ajax(this);

    You must have a max number of desired re-tries for the API call, otherwise your code will not stop trying :)

    $(".apiGateway").on("click", function (e) {
        let maxAttempts = 5,
            countAttempts = 0;
    
        e.preventDefault();
       
        $.ajax({
            url: 'apiGatewayURL',
            method: 'GET',
            error: function (xhr) {
                if (xhr.status === 503 && countAttempts < maxAttempts) {
                    alert('fail');
                    ++countAttempts;
                    $.ajax(this);
                }
            }
        });
    });