Leonardo Leonardo - 2 months ago 12
Javascript Question

Configure jQuery to retry ajax calls if they fail

I have all my ajax calls in a custom JS file. And trust me there are alot of them!
I would like to implement a "retry on fail behavior" in all ajax calls.

Is there a way to do it like "interception"? Or do I have to do it one by one?

My fear here is that a future dev will forget to set the retry policy...

Sample ajax call:

url: apiRoot + 'reservationItens?reservaId=' + idReservation + '&bagId=' + idBag,
type: 'PUT',
success: function () {
if (onSuccess != null) {
error: function (x, y, z) {
if (onError != null) {
onError(x, y, z);


You can create api method for ajax calls, just like this one. In the ajaxApi function you can create your own handlers. For example for success or error events, thanks to this developer using this api can attach his handlers, without worrying what else handlers to attach.

function outerSuccesFN() {

function outerErroFN() {

function completeFn() {

function ajaxApi(url, dataType, data, timeout) {

    var ajaxResults = $.ajax({
        url: url,
        dataType: dataType,
        data: data,
        timeout: timeout

    function mySuccesFn() {

    function myErroFn() {

    return ajaxResults.done(mySuccesFn).fail(myErroFn);

var ajaxResult = ajaxApi('http://api.jquery.com/jsonp/', 'jsonp', {
    title: 'ajax'
}, 15000);