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?
Dougs answer is correct, but you actually can use
$.getJSON
and catch errors (not having to use$.ajax
). Just chain thegetJSON
call with a call to thefail
function: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/
Yes, it's built in to jQuery. See the docs at jquery documentation.
ajaxError may be what you want.
You will need to either use the lower level $.ajax call, or the ajaxError function. Here it is with the $.ajax method:
EDIT I added a
timeout
to the$.ajax
call and set it to five seconds.I prefer to this approach because you can return the promise and use .then(successFunction, failFunction); anywhere you need to.
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)