skip to Main Content

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')
                   }
                }
            })
        

    })

2

Answers


  1. You can create a function and call it on error again but you need to consider it would create an infinite loop if the server keep sending 503:

    function sendAjax(url, method, body, callback) {
        $.ajax({
            url: url,
            method: method,
            error: function (xhr) {
                if (xhr.status === 503) {
                    sendAjax(url, method, body, callback);
                }
            }
        })
    }
    
    Login or Signup to reply.
  2. 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);
                }
            }
        });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search