10

I have seen that you can specify what to do generally if an ajax request fails, is it possible to have it try again in some sort of a loop so that it tries at least x amount of times before it stops? I have used this code before:

$.ajaxSetup({
  "error":function() {   
    alert("error");
}});

Which will apply to all AJAX requests (correct me if I'm wrong).

I want to do something like this:

$.ajaxSetup({
  "error":function() {   
    $(this).ajax;
}});

Would this work? Or even better: would this be the right way to do it? I would wrap the retry in a count system so that it doesn't infinitely retry. In my application 9 times out of 10 it will work correctly but every now and then one of the APIs I'm interfacing with will return an error.

Any suggestions would help, thanks!

Doug Molineux
  • 12,283
  • 25
  • 92
  • 144
  • 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 14:02

1 Answers1

13

You can try something like this:

    var attempts;
    function doAjaxRequest() {
        attempts = 0;
        doAjaxRequestLoop();
    }

    function doAjaxRequestLoop() {
        attempts += 1;
        if (attempts > 10) {
            alert('too many attempts.');
            return;
        }

        $.ajax({ // do your request
            error: function (error) {
                doAjaxRequestLoop();
            }
        });
    }

</script>

Although I might recommend against it. If the request fails you may want to find out why it failed. What if the user lost their internet connect? Any further attempts are likely to fail again so why retry?

Lucas Sampaio
  • 1,568
  • 2
  • 18
  • 36
Jay
  • 6,224
  • 4
  • 20
  • 23
  • 2
    You need to call `doAjaxRequestLoop` inside `doAjaxRequest`. Right now it just sets the value to 0 and never does anything. – James Montagne Jun 09 '11 at 20:15
  • Your right! That's what I get for being in a rush. Post updated. – Jay Jun 09 '11 at 20:17
  • Thanks! So for some reason one of the client APIs I'm working with seems really flimsy, most of the time it works but every now and then a request will timeout. If I could make it try at least one more time, I think that would make it solid enough. I think this is a good way to do it, thanks Jay – Doug Molineux Jun 09 '11 at 20:17
  • One more use case: right now Cloudflare throws random 520 errors every now and then (started happening a month ago on many free accounts simultaneously, Cloudflare chose to deny responsibility). If you simply retry a failed request, it works. Making all Ajax requests simply try again on 520 makes the problem go away for the users. – Marassa Aug 27 '21 at 08:40