Javascript – What’s the best way to retry an AJAX request on failure using jQuery

ajaxjavascriptjqueryxmlhttprequest

Pseudo code:

$(document).ajaxError(function(e, xhr, options, error) {
  xhr.retry()
})

Even better would be some kind of exponential back-off

Best Solution

Something like this:


$.ajax({
    url : 'someurl',
    type : 'POST',
    data :  ....,   
    tryCount : 0,
    retryLimit : 3,
    success : function(json) {
        //do something
    },
    error : function(xhr, textStatus, errorThrown ) {
        if (textStatus == 'timeout') {
            this.tryCount++;
            if (this.tryCount <= this.retryLimit) {
                //try again
                $.ajax(this);
                return;
            }            
            return;
        }
        if (xhr.status == 500) {
            //handle error
        } else {
            //handle error
        }
    }
});