jQuery: Handle fallback for failed AJAX Request jQuery: Handle fallback for failed AJAX Request jquery jquery

jQuery: Handle fallback for failed AJAX Request


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.


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/


Yes, it's built in to jQuery. See the docs at jquery documentation.

ajaxError may be what you want.