Interactive by Nature

Error Handling With jQuery.get()

One of the things I love about my job is that I’m always learning something new. They encourage me to keep up with the latest technology and trends. My latest discovery was error handling with $.get().

As of jQuery 1.5, you can set an error handler after making an ajax request using $.get() via the jQuery XHR object, which allows you to chain the .error() callback after the request is complete. “This jQuery XHR object, or ‘jqXHR,’ returned by $.get() implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see Deferred object for more information)”.

The code looks a little something like this:

$.get('url', function() {
    alert("success");
})
.error(function() {
    alert("error");
})

Another snazzy way of dealing with error handling for $.get() as of jQuery 1.5, pointed out by my good community friend @tehraven, is deferred.fail().

And it goes a lil somethin’ like this:

$.get("url")
.done(function(){ 
    alert("success");
})
.fail(function(){
    alert("error(fail)");
});

Before jQuery 1.5, you would have to use something like $.ajaxSetup() to predefine a default error callback. Note: $.ajaxSetup() must be set before making the ajax call.

$.ajaxSetup() example:

$.ajaxSetup({
  error: function(xhr, status, error) {
    alert("error");
  }
});

You could also use the .ajaxError() method, which involves too much prep work for my taste.

.ajaxError() example:

$(document).ajaxError(function(e, xhr, settings, exception) { 
    alert("error"); 
});

I find that the $.get().error() chaining method is more efficient as it involves the least amount of lines of code. And when you’re working with the mobile web, every line counts.

Comments

  1. Thanks for the info. Great blog!

    nash44 on August, 22nd, 2011 at 10:22 am

Leave a Comment