1

I need a way to set some kind of timeout function globally with $.ajaxSetup that will allow my Phonegap application to keep retrying an ajax GET or POST every time there is a timeout due to a bad internet connection.

I use Backbone.js so most jquery plugins won't work for this, I would some help writing one global piece of code which will handle retries.

Thank you.

Ilya Karnaukhov
  • 3,838
  • 7
  • 31
  • 53
  • 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:01

2 Answers2

4

You can use jQuery.ajaxSetup(options).

Set default values for future Ajax requests. Its use is not recommended.

Example

$.ajaxSetup({
  timeout: TimeoutValue
});

Apart from that if you want perform call again on timeout, I will suggest you to create wrapper for ajax call like.

function myAjax(options){
    var myOptions = {
        timeout: TimeoutValue,
        error: function( jqXHR, textStatus, errorThrown) {
            //textStatus can one of these "timeout", "error", "abort", and "parsererror"
            if(textStatus === "timeout") {
                //Recall method once again
                myAjax(options)
            }
        }           
    };

    options = $.extend(true, myOptions , options);
    $.ajax(options)
}

And Use the function just like $.ajax

Satpal
  • 132,252
  • 13
  • 159
  • 168
  • Hi Satpal, this is a good answer, but I need a global function that will handle ALL my application calls, this is why I wanted some kind of function done using $.ajaxSetup only. – Ilya Karnaukhov Aug 27 '14 at 10:23
1

Found a solution to make all AJAX calls work with a retry timeout.

$(document).ajaxError(function (e, xhr, options) {
    if(xhr.status == 0){
        setTimeout(function(){
            console.log('timeout, retry');
            $.ajax(options);
        }, 5000);
    }
});
Ilya Karnaukhov
  • 3,838
  • 7
  • 31
  • 53