Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

What is the 3 parameters of load () method?

This callback function has three different parameters: parameter 1: It contains the result of the content if the method call succeeds. parameter 2: It contains the status of the call function. parameter 3: It contains the XMLHttpRequest object.

Which is the correct syntax for load a remote page using an HTTP request?

Syntax: $(selector). load(URL,data,callback);

Which method is used on the returned object of Ajax () method if the Ajax call fails?

If an AJAX request fails, you can react to the failure inside the callback function added via the fail() function of the object returned by the $. ajax() function. Here is a jQuery AJAX error handling example: var jqxhr = $.


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.


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!");
    }
});

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);
});