5

I have a jquery-ajax call to an action in the controller. Sometimes the call is failing so I would like to retry again.

jQuery-ajax:

return ajax({
    url: getRootDir() + urlDoTask, // urlDoTask is something like "/Action/"
    data: { param: someParam },
    type: 'POST',
    dataType: 'json',
    tryCount: 0,
    retryLimit: 3
}).then(function (data) {
    // Do some stuff
    return ....
}, function (xhr, textStatus, errorThrown) {

    if (textStatus == 'timeout' || (xhr.responseText == "" && textStatus == 'error')) {
        this.tryCount++; // this is always 1
        if (this.tryCount <= this.retryLimit) {
            //try again
            $.ajax(this);
            return;
        }
        return; // this point is never reached
    }
    if (xhr.status == 404) {
        // Do some stuff
    }

    return ... // I want to reach it after this.tryCount > this.retryLimit
});

function getRootDir() {
    var loc = window.location.pathname;
    var dir = loc.substring(0, loc.lastIndexOf('/'));

    return dir;
}

Above code is not working, tryCount is always 1 each time ajax-call fails. Also, once this.tryCount is greater than this.retryLimit, last return is never reached.

Ideas?

Greg
  • 481
  • 1
  • 5
  • 21
Willy
  • 9,848
  • 22
  • 141
  • 284
  • You can see my comment below for the reason why its happening. But I would recommend you do the retry over the whole ajax call instead of within it. That way, you can have an outer stateful object to manage your retry controls. – Jerico Sandhorn Nov 03 '13 at 13:12
  • Maybe try the notation in http://stackoverflow.com/a/10024557/694325 - I'm not sure if that notation messes with scope or something. Did you manage to fix this issue? – Joel Peltonen Jan 31 '14 at 07:03
  • possible duplicate of [How do I resend a failed ajax request?](http://stackoverflow.com/questions/8881614/how-do-i-resend-a-failed-ajax-request) – user2284570 Oct 10 '14 at 19:24
  • Possible duplicate of [What's the best way to retry an AJAX request on failure using jQuery?](https://stackoverflow.com/questions/10024469/whats-the-best-way-to-retry-an-ajax-request-on-failure-using-jquery) – gdvalderrama Jul 07 '17 at 08:53

1 Answers1

1

There are few things I see. The arguments passed in are not actually members of the object. Its just a JSON map of key/pair. So things like "this.tryCount" will not exist in the function. What you can do is put alerts in your function (or debug) and see what the values are. Probably they are undefined or 0.

Jerico Sandhorn
  • 1,880
  • 1
  • 18
  • 24
  • Thanks for your comment but could you indicate me how to retry the same ajax call on failure, that is, call the same action in the controller once it has failed. An piece of example would be highly appreciated. – Willy Nov 03 '13 at 14:59