Loading content with jQuery AJAX and dealing with failures
Posted February 6th, 2009 in Javascript
Some of the last few jQuery posts on this blog have looked at loading content with jQuery AJAX, selecting the element to inject and using a loading image. In these posts I incorrectly noted that the .load() method does not allow for error reporting and therefore you cannot deal with failures so another method would be required. Having had a better read of the jQuery docmentation I now know you can deal with failures when using .load() so this post looks at how to do this.
There are other was of loading remote content with jQuery and I will look at how to do these in future posts. Make sure you subscribe to my RSS feed (details at the end of this post) so you don't miss out.
The examples used in the post were tested and work in jQuery 1.2.6 and should also work in other jQuery 1.2 versions and in version of jQuery >= 1.3
The .load() method takes three parameters:
- The URL to load the content from
- The data to pass in the GET string (I'll look at this in another post)
- The callback function to call after the request has finished.
So, if you had a couple of buttons and a placeholding <div> like this:
<input type="button" onclick="example_ajax_request('/examples/ajax-loaded.html')" value="This will work" />
<input type="button" onclick="example_ajax_request('/examples/file-does-not-exist.html')" value="This will fail" />
<div id="example-placeholder">
<p>Placeholding text</p>
</div>
Then you could load the content into #example-placeholder as in the following example, changing the text to "There was an error making the AJAX request" if there was a failure to retrieve the data:
function example_ajax_request(url) {
$('#example-placeholder').load(url, "",
function(responseText, textStatus, XMLHttpRequest) {
if(textStatus == 'error') {
$('#example-placeholder').html('<p>There was an error making the AJAX request</p>');
}
}
);
}
Here's the above code in action:
Placeholding text
Pretty simple, huh?! You can of course do a lot more than what I've done in my example but this should be a useful start.
Related posts:
- Make jQuery Facebox loading screen auto-center (Tuesday, June 30th 2009)
- How to tell if an element exists with jQuery (Friday, April 10th 2009)
- Loading content with jQuery AJAX - using a loading image (Tuesday, February 3rd 2009)
- Loading content with jQuery AJAX - selecting the element to inject (Sunday, January 18th 2009)
- Loading content with jQuery AJAX (Wednesday, January 14th 2009)
Share or Bookmark
Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.
Subscribe or Follow
Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.
