jQuery: Handle fallback for failed AJAX Request
Solution 1
You will need to either use the lower level $.ajax call, or the ajaxError function. Here it is with the $.ajax method:
function update() {
$.ajax({
type: 'GET',
dataType: 'json',
url: url,
timeout: 5000,
success: function(data, textStatus ){
alert('request successful');
},
fail: function(xhr, textStatus, errorThrown){
alert('request failed');
}
});
}
EDIT I added a timeout
to the $.ajax
call and set it to five seconds.
Solution 2
Dougs answer is correct, but you actually can use $.getJSON
and catch errors (not having to use $.ajax
). Just chain the getJSON
call with a call to the fail
function:
$.getJSON('/foo/bar.json')
.done(function() { alert('request successful'); })
.fail(function() { alert('request failed'); });
Live demo: http://jsfiddle.net/NLDYf/5/
This behavior is part of the jQuery.Deferred interface.
Basically it allows you to attach events to an asynchronous action after you call that action, which means you don't have to pass the event function to the action.
Read more about jQuery.Deferred here: http://api.jquery.com/category/deferred-object/
Solution 3
I prefer to this approach because you can return the promise and use .then(successFunction, failFunction); anywhere you need to.
var promise = $.ajax({
type: 'GET',
dataType: 'json',
url: url,
timeout: 5000
}).then(function( data, textStatus, jqXHR ) {
alert('request successful');
}, function( jqXHR, textStatus, errorThrown ) {
alert('request failed');
});
//also access the success and fail using variable
promise.then(successFunction, failFunction);
Solution 4
Yes, it's built in to jQuery. See the docs at jquery documentation.
ajaxError may be what you want.
Solution 5
I believe that what you are looking for is error option for the jquery ajax object
getJSON is a wrapper to the $.ajax
object, but it doesn't provide you with access to the error option.
EDIT: dcneiner has given a good example of the code you would need to use. (Even before I could post my reply)
Related videos on Youtube
Patrick Oscity
Updated on June 22, 2020Comments
-
Patrick Oscity almost 4 years
Can jQuery provide a fallback for failed AJAX calls? This is my try:
function update() { var requestOK = false; $.getJSON(url, function(){ alert('request successful'); requestOK = true; }); if (!requestOK) { alert('request failed'); } }
Unfortunately, even if the callback function of the $.getJSON() method is called, i get the message 'request failed', before the callback function has the opportunity to set the requestOK variable. I think it's because the code runs in parallel. Is there a way to handle such situations? I thought about chaining or some way of waiting for the AJAX request, including its callback function. But how? Does anyone know how to do that?
-
Patrick Oscity over 14 yearsthat's already great! but it doesn't seem to work, if the internet connection is down :(. that's quite important, because i'm developing a dashboard widget for osx and want to display some kind of message, saying that a request was not possible. any other tips?
-
Doug Neiner over 14 years@Patrick, I updated my answer to include the
timeout
parameter. It should call the error function after 5 seconds if the internet connection is down. -
Patrick Oscity over 14 yearssorry for all the double question trouble and so on! i opened a new question because i thought, that my original question was basically answered and it would be more appropriate to move it to a new one. didn't know that the answer to my second question had so much to do with my first one ;) nevertheless, i cheered to soon. still doesn't fall back to the error function, even if i set the timeout parameter to 1, which would be absolutely unrealistic. is it possible that the timeout parameter is overridden by something else?
-
Doug Neiner over 14 yearsNo worries, I was being to sensitive. Let me look into it more. Since you do have the other question now, I will post my findings over there :)
-
Cobby about 11 years
.error()
is deprecated as of jQuery v1.8 and you should use.fail()
. -
Fydo over 10 yearsWrong about getJSON not give access to errors. You can access the error option by form of chaining the getJSON call. See @Lasse Dahl Ebert's answer.
-
Sean Vieira over 10 years@Fydo - this answer actually predates jQuery's Deferred by over a year ;-) At the time, there was now way to get access to the error, you had to drop down to the
$.ajax
method. -
tom over 4 yearsWorks for me, exactly when the server is down or the session is stale. Thanks!!!