Following on from my last post on integrating HTML content from another system into an existing site, I realized I wasn't handling failures very gracefully. To recap, I was using the load
method of jQuery:
$(document).ready(function() {
$('#races a').click(function () {
$('#results').load(
'Racing/' + $(this).attr('href') + '
#wrap');
return false;
});});
I was surprised to find there wasn't much information about how to go about capturing an error if it occurs. It turns out you can get it by passing a callback function to the load function. This function accepts 3 parameters: responseText, textStatus and an XMLHttpRequest. I'm not exactly sure why they decided to give you responseText and textStatus when you have an XMLHttpRequest (an object that already encapsulates both of these values so passing them as parameters is a violation of the DRY principle).
Anyways, here is how to do it using the callback function:
$(document).ready(function() {
$('#races a').click(function () {
$('#results').load('Racing/' + $(this).attr('href') + ' #wrap', "", function(responseText, textStatus, XMLHttpRequest) {
switch (XMLHttpRequest.status) {
case 200: break;
case 404:
$('#results').html('<p>Looks like the results have not been uploaded to the server yet. Please check back later.</p>');
break;
default:
$('#results').html('<p>' + XMLHttpRequest.status + ': ' + XMLHttpRequest.statusText + '. Please contact the club and let them know.</p>');
break;
}
});
return false;
});
});
Now you can get specific about how you report your error based on the response code. For example, if you see something in the 400 range you know there has been a client problem (e.g. 404 not found), versus a 500 series status for server side problems. In this case, I explicitly handle 404 errors and have a generic catch-all for anything else.
Posted by: Erick Dovale | 2009.05.15 at 11:07 AM
Posted by: BBG | 2009.06.05 at 01:16 PM
Posted by: Christian | 2011.05.05 at 05:08 PM