How to detect JQuery $.get failure? Seeking simple code example

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.


.get() is just a synonym for .ajax() with a number of options pre-set. Use ajax() to get the full range of options, including the error callback.

$.ajax({
type: "GET",
url: "test.htm",
error: function(xhr, statusText) { alert("Error: "+statusText); },
success: function(msg){ alert( "Success: " + msg ); }
}
);

As of jQuery 3.0 .success() and .error() are depreciated.
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/

Tags:

Jquery