I'm using jQuery's .load()
method to retrieve some data when a user clicks on a button.
After the load successfully finishes, I show the result in a <div>
.
The problem is, sometimes an error occurs in load()
while retrieving the data.
How can I catch an error in load()
?
load() documentation.
Just a little background on how a load error happens...
Edit: Added a path other than the root path as requested by comments.
Besides passing a callback to the load() function as Ólafur Waage suggests, you can also register "global" error handlers (global as in global for all ajax calls on the page).
There are at least two ways to register global Ajax error handlers :
Register just the error handler with
ajaxError()
:Or, use
ajaxSetup()
to set up an error handler and other properties at the same time:Electric toolbox has an article called "Loading content with jQuery AJAX and dealing with failures" that appears to answer your question.
Apparently the callback function that you specify gets passed the response, status, and XmlHttpRequest object, allowing you to determine the status of your ajax request and handle the condition accordingly.
load() offers a callback.
This is how its done IIRC. (haven't tested it)