views:

428

answers:

3

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?

A: 

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

ajaxError may be what you want.

Jonathon
+3  A: 

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');
    },
    error: function(xhr, textStatus, errorThrown){
       alert('request failed');
    }
  });
}

EDIT I added a timeout to the $.ajax call and set it to five seconds.

Doug Neiner
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?
padde
@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
thanks a ton! works perfectly!
padde
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?
padde
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
A: 

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