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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With