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

56,833

Solution 1

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

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

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);
});
Share:
56,833
Tot Zam
Author by

Tot Zam

Updated on April 06, 2020

Comments

  • Tot Zam
    Tot Zam about 4 years

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

    • colm.anseo
      colm.anseo over 5 years
      This question is from 2009, so please note from $.load: Prior to jQuery 3.0, the event handling suite also had a method named .load(). Older versions of jQuery determined which method to fire based on the set of arguments passed to it.
  • David Dombrowsky
    David Dombrowsky about 14 years
    thanks for the link to the jquery docs. I didn't know they even existed!
  • Enrico Detoma
    Enrico Detoma almost 13 years
    The first argument of the function IS responseText. No need to use XMLHttpRequest.responseText...
  • Resh32
    Resh32 over 11 years
    Thanks - load failures are mostly due to a problem when loading the target page.
  • Dee
    Dee about 3 years
    i'm using jquery 3.5, and it has no $.ajaxError function, although it's still in documentation: api.jquery.com/ajaxError
  • Dee
    Dee about 3 years
    As of jQuery 1.9, it's $(document).ajaxError instead of just $.ajaxError