Resending AJAX request

Wai Park Soon
NoteToPS
Published in
1 min readJan 28, 2013

jQuery makes it easy to use AJAX and bind it with various handlers such as success and error. Sometimes we would like to re-attempt an AJAX request if any error occurs, this could be achieved by introducing two additional configs in its AJAX settings.

$.ajax({
type: ‘post’,
url: ‘http://example.com/handleAjax',
data: myData,
attemptCount: 0,
attemptLimit: 5,
error: function (data, textStatus, errorThrown) {
var s = this; // The config we used
s.attemptCount++;
if (s.attemptCount < s.attemptLimit) {
$.ajax(s);
} else {
alert(“AJAX failed.”);
}
}
});

attemptCount and attemptLimit are introduced to track the current status of re-attempting. The key here is that the this keyword inside the handler functions is actually the config object that we used to configure the AJAX request.

--

--