Home / Loading content with jQuery AJAX and dealing with failures

Loading content with jQuery AJAX and dealing with failures

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:

  1. The URL to load the content from
  2. The data to pass in the GET string (I’ll look at this in another post)
  3. 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.