44

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
  • 53,604
  • 17
  • 144
  • 168

5 Answers5

91

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.

Julian Camilleri
  • 2,975
  • 1
  • 25
  • 34
Doug Neiner
  • 65,509
  • 13
  • 109
  • 118
  • that'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? – Patrick Oscity Dec 04 '09 at 02:32
  • @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. – Doug Neiner Dec 04 '09 at 02:51
  • sorry 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? – Patrick Oscity Dec 04 '09 at 03:25
  • No 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 :) – Doug Neiner Dec 04 '09 at 03:35
  • Works for me, exactly when the server is down or the session is stale. Thanks!!! – tom Nov 23 '19 at 22:51
14

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/

Lasse Skindstad Ebert
  • 3,370
  • 2
  • 29
  • 28
3

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

ajaxError may be what you want.

Jonathon Faust
  • 12,396
  • 4
  • 50
  • 63
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);
thebaron24
  • 315
  • 3
  • 8
2

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)

Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
  • Wrong 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. – Fydo Jan 28 '14 at 12:39
  • 1
    @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. – Sean Vieira Jan 28 '14 at 15:32