Malcolm G
Malcolm G

Reputation: 614

How to retry Ajax call using reference with Success and Failure handlers

I am trying to see if it is possible to store the reference to an ajax call on failure, and then retry the call later. I have tried the following:

$.ajax({
    url: "controller/action",
    data: {
        params: "here"
    }
})
.success(function (response) {
    DoStuffHere();
})
.fail(function (error) {
    ajaxRef = this;
    DoOtherStuff();
})

Where DoOtherStuff attempts to make the ajax call using the reference as follows:

function DoOtherStuff() {
    if(ajaxRef)
    {
        $.ajax(ajaxRef);
    }
}

Obviously, this is oversimplified to demonstrate what I'm trying to accomplish.

It seems that this actually does make the ajax call, but the problem is that it doesn't seem to keep a reference to the success or fail attributes of the call. So when the call comes back successfully, it doesn't call DoStuffHere();

In my searching for an answer to this question, I found code that says that it works if you call $.ajax(this) inside the success or fail function, but in my case, I need to run certain other functions and ajax calls prior to retrying.

Is there any way to make it so that the success and fail are carried with the reference to the ajax call?

Upvotes: 1

Views: 53

Answers (2)

Malcolm G
Malcolm G

Reputation: 614

I just figured out why this wasn't working. I'm not sure why I've learned to use the .success() and .fail() handlers for ajax, but apparently they don't stick around with the reference that way. So when I change the code to the following:

$.ajax({
    url: "controller/action",
    data: {
        params: "here"
    },
    success: function (response) {
        DoStuffHere();
    },
    error: function (error) {
        ajaxRef = this;
        DoOtherStuff();
    }
})

Then this actually works:

function DoOtherStuff() {
    if(ajaxRef) {
        $.ajax(ajaxRef);
    }
}

Hope this is helpful to someone out there!

Upvotes: 1

Manuel Otto
Manuel Otto

Reputation: 6540

Have you tried attaching the succes/failure handlers to the ajax request object itself? Something like this:

var ajaxRef = {
    url: "controller/action",
    data: {
        params: "here"
    },
    success: ajaxSuccess,
    error: ajaxFailure
}

$.ajax(ajaxRef)

function ajaxSuccess(response){
    DoStuffHere();
}
function ajaxFailure(error){
    DoOtherStuff();
}

function DoOtherStuff() {
    if(ajaxRef)
    {
        $.ajax(ajaxRef);
    }
}

Upvotes: 1

Related Questions