[jquery] 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?

This question is related to jquery ajax json callback wait

The answer is


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);

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

ajaxError may be what you want.


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)


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/


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to callback

When to use React setState callback How to send an HTTP request with a header parameter? javascript function wait until another function to finish What is the purpose of willSet and didSet in Swift? How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()? Aren't promises just callbacks? How do I convert an existing callback API to promises? How to access the correct `this` inside a callback? nodeJs callbacks simple example Callback after all asynchronous forEach callbacks are completed

Examples related to wait

How to make the script wait/sleep in a simple way in unity How do I make a delay in Java? Wait some seconds without blocking UI execution Protractor : How to wait for page complete after click a button? How to wait until an element is present in Selenium? Javascript sleep/delay/wait function How to wait till the response comes from the $http request, in angularjs? How to add a "sleep" or "wait" to my Lua Script? Concept behind putting wait(),notify() methods in Object class How can I wait for 10 second without locking application UI in android