d-_-b
d-_-b

Reputation: 23211

ajax timeout callback function

Is there a way to run a function if jQuery's $.ajax function hits it's timeout?

i.e.

$.ajax({
...
...
,timeout:1000(){do something if timeout)
...

});

Upvotes: 25

Views: 48175

Answers (1)

Dan-Nolan
Dan-Nolan

Reputation: 6657

$.ajax({
    ...
    timeout: 1000,
    error: function(jqXHR, textStatus, errorThrown) {
        if(textStatus==="timeout") {
           //do something on timeout
        } 
    }
});​

For more information check out the jQuery documentation:

http://api.jquery.com/jQuery.ajax/


Edited

It's been over a year since I initially answered this and the textStatus possible values have changed to "success", "notmodified", "error", "timeout", "abort",or"parsererror". For error callbacks, only the last four statuses are possible.

Also you can now wire your error handlers through the returned JQuery deferred promise object's .fail method:

var promise = $.ajax({ timeout: 1000 });

promise.fail(function(jqXHR, textStatus) {
    if(textStatus==="timeout") {
        // handle timeout  
    }
});

Upvotes: 48

Related Questions