Search code examples
jqueryajaxjsoncallbackwait

jQuery: Handle fallback for failed AJAX Request


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?


Solution

  • 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.