Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically try AJAX request again on Fail

Tags:

jquery

ajax

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!

like image 949
Doug Molineux Avatar asked Jun 09 '11 20:06

Doug Molineux


1 Answers

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?

like image 87
Jay Avatar answered Oct 18 '22 15:10

Jay