How to catch error in jQuery's load() method

JqueryAjaxError HandlingLoad

Jquery Problem Overview


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()?

Jquery Solutions


Solution 1 - Jquery

load() documentation.

Just a little background on how a load error happens...

$("body").load("/someotherpath/feedsx.pxhp", {limit: 25}, 
    function (responseText, textStatus, req) {
        if (textStatus == "error") {
          return "oh noes!!!!";
        }
});

Edit: Added a path other than the root path as requested by comments.

Solution 2 - Jquery

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():

$.ajaxError(function(event, request, settings) {
      alert("Oops!!");
});

Or, use ajaxSetup() to set up an error handler and other properties at the same time:

$.ajaxSetup({
    timeout: 5000,
    error: function(event, request, settings){
        alert("Oops!");
    }
});

Solution 3 - Jquery

load() offers a callback.

> Callback.
The function called when the ajax request is complete (not necessarily success).

This is how its done IIRC. (haven't tested it)

$("#feeds").load("feeds.php", {limit: 25}, 
    function (responseText, textStatus, XMLHttpRequest) {
        // XMLHttpRequest.responseText has the error info you want.
        alert(XMLHttpRequest.responseText);
});

Solution 4 - Jquery

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionM AungView Question on Stackoverflow
Solution 1 - JquerycgpView Answer on Stackoverflow
Solution 2 - Jquerymatt bView Answer on Stackoverflow
Solution 3 - JqueryÓlafur WaageView Answer on Stackoverflow
Solution 4 - JqueryvezultView Answer on Stackoverflow