Handling Errors With jQuery.load

If you attended the SoundByte that I ran today then this is a very quick follow-up post to get you started with handling errors with the simple example I used. If you don't know what a SoundByte is, or worse don't have an ADC Contract, you can get in touch with my team via this blog J

In the SoundByte one thing I demonstrated was using jQuery's ".load" function to do quick and easy partial page rendering. What I didn't show was how to deal with errors; it is essential that you handle script or Ajax errors correctly as otherwise you could end up rendering a page unusable in the event of an error, and you're likely to lose visitors. Additionally, it is important to give the user feedback that something is happening when waiting on a request from the server.

A Sample Site

Attached to this post is a really simple (and ugly as I'm writing this quickly on a crowded train to Reading!) demo web site that we can use to walk through the options, so grab that, unzip it, and open it up. You'll notice I've actually created 4 JavaScript files, but only one is actually referenced in Default.aspx. As we progress through this post, you should uncomment only the script we are using (e.g. comment out A_NoHandling.js and uncomment B_NoHandlingWithLoadProgress).

Try the page – basically you can cause a ".load" call to get the current time, but if you check the "cause error" box the server will throw an exception. The server call waits 2 seconds to simulate network latency.

Script A: No error handling

With Script A you should notice that the page functions fine when the server does not cause an error. However, when there is an error, the .load function automatically ignores the returned content, and the user has no idea something happened. Additionally, you might not think you clicked on the button correctly as it isn't obvious that the load is happening.

Let's address one of these and look at Script B...

Script B: Callback error handling

In Script B I am using the 3rd argument to the .load operation to supply a callback function. This is called when the load finishes, whether it succeeded or not. The code to supply this callback looks like this;

$('#contentregion').load('PartialPage.aspx?' + data, null, callback);

Easy huh? In the callback I check whether or not the load was successful as follows;

if (responseStatus !== 'success') {

    var errormsg = ...; // build up error message

    $('#messageregion').html(errormsg);

}

If it failed (in which case responseStatus would likely be "error"), we display a message in a dedicated div. However, note that I still don't know when requests are in progress. I'd also have to supply this callback for every single Ajax call I made on a page, which can become a pain and is prone to being forgotten.

Script C: Global error handling

jQuery also provides a global .ajaxError function. This is fired whenever any Ajax call on a page fails, so I can move my error handling code into this;

$('#messageregion').ajaxError(function(event, xhr, options) {

    var errormsg = ...;

    $(this).html(errormsg);

});

Here we are saying that whenever any Ajax error occurs on a page, extract an error message, select the "messageregion" div's content, and replace it with the error message. My .load call is also simplified as I don't need to supply a callback anymore;

$('#contentregion').load('PartialPage.aspx?' + data);

However, I still don't know when an Ajax call is in progress, so the page doesn't feel responsive.

Script D: Global errors and responsiveness indicators

The great news is that jQuery not only provides a global ajaxError event, but it also provides quite a few others - .ajaxComplete, .ajaxSend, .ajaxSuccess, .ajaxStart, .ajaxStop, etc. The last of these two are ideal to implement some kind of load progress feedback – we simply display something when an Ajax call starts, and update it when the call finishes;

$('#loadingregion').ajaxStart(function() {

    $(this).html('<b>Loading...</b>');

});

$('#loadingregion').ajaxStop(function() {

    $(this).html('Done');

});

And that's it! Try the page now and we have both a responsive page and one that handles server-side failures properly in script. I hope that helps you get started.

jQueryErrors.zip