Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect jQuery $.get failure?

Tags:

jquery

I'm a jQuery beginner. I'm trying to code a very simple using $.get(). The official documentation says:

If a request with jQuery.get() returns an error code, it will fail silently unless the script has also called the global .ajaxError() method or.

As of jQuery 1.5, the .error() method of the jqXHR object returned by jQuery.get() is also available for error handling.

So, if all goes well, my callback function for success will be called. However, if the request fails, I would like to get the HTTP code :404, 502, etc and formulate a meaningful error message for the user.

However, since this is an asynchronous call I can imagine that I might have several outstanding. How would .ajaxError() know which request it corresponds to? Maybe it would be better to use the .error() method of the jqXHR object returned by jQuery.get()?

I am seeking an extremely simple code example. Perhaps the success routine calls Alert("Page found") and the failure routine checks for 404 and does an Alert("Page not found").

Update

The following page is extremely helpful: http://api.jquery.com/jQuery.get/

like image 924
Mawg says reinstate Monica Avatar asked Feb 19 '11 00:02

Mawg says reinstate Monica


2 Answers

You're right that you can use jQuery 1.5's new jqXHR to assign error handlers to $.get() requests. This is how you can do it:

var request = $.get('/path/to/resource.ext');  request.success(function(result) {   console.log(result); });  request.error(function(jqXHR, textStatus, errorThrown) {   if (textStatus == 'timeout')     console.log('The server is not responding');    if (textStatus == 'error')     console.log(errorThrown);    // Etc }); 

You can also chain handlers directly onto the call:

$.get('/path/to/resource.ext')      .success(function(result) { })      .error(function(jqXHR, textStatus, errorThrown) { }); 

I prefer the former to keep the code less tangled, but both are equivalent.

like image 195
Dave Ward Avatar answered Sep 21 '22 17:09

Dave Ward


As of jQuery 3.0 .success() and .error() are deprecated.
You can use .done() and .fail() instead

$.get( url )     .done(function( data, textStatus, jqXHR ) {         console.log(data);     })     .fail(function( jqXHR, textStatus, errorThrown ) {         console.log(jqXHR);         console.log(textStatus);         console.log(errorThrown );     }); 

Source: https://api.jquery.com/jQuery.ajax/

like image 42
stallingOne Avatar answered Sep 20 '22 17:09

stallingOne