Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 884
Patrick Oscity Avatar asked Dec 04 '09 01:12

Patrick Oscity


People also ask

What happens if an Ajax request made using jQuery fails?

version added: 1.0. Whenever an Ajax request completes with an error, jQuery triggers the ajaxError event. Any and all handlers that have been registered with the . ajaxError() method are executed at this time.

What is jqXHR in Ajax?

The jqXHR Object. The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser's native XMLHttpRequest object. For example, it contains responseText and responseXML properties, as well as a getResponseHeader() method.

How to use Ajax in jQuery?

The ajax() method in jQuery is used to perform an AJAX request or asynchronous HTTP request. Parameters: The list of possible values are given below: type: It is used to specify the type of request. url: It is used to specify the URL to send the request to.


1 Answers

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.

like image 112
Doug Neiner Avatar answered Sep 18 '22 16:09

Doug Neiner