What's the best way to retry an AJAX request on failure using jQuery?

Tom Lehman picture Tom Lehman · Apr 5, 2012 · Viewed 96.3k times · Source

Pseudo code:

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

Even better would be some kind of exponential back-off

Answer

Sudhir Bastakoti picture Sudhir Bastakoti · Apr 5, 2012

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