views:

50

answers:

2

I use $.get, $.post, and $.getJSON extensively, so I wanted to see how .ajaxError worked. I tried this...

$(document).ajaxError(function (e, xhr, options, error)
{
    console.log(e);
    console.log(xhr);
    console.log(options);
    console.log(error);
});

and I also tried putting it inside my $(document).ready().. And then I disabled my network connection. A slew of errors flew up from the timed POSTs in AJAX (because they were getting unexpected responses), and the GETs were coming back instantaneously (cached), but nothing else appeared in Firebug, as if ajaxError were never being called. What am I doing wrong? I just tried again with no console logs and just alert('foo'), and again nothing happened. Lots of errors, but ajaxError never firing.

A: 

I got the following sample to work from the jQuery doc.

http://api.jquery.com/ajaxError/

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>jQuery Sandbox</title>
  </head>
  <body>
    <div class="trigger">Trigger</div>
    <div class="result"></div>
    <script type="text/javascript" src="../scripts/jquery-1.4.js"></script>
    <script type="text/javascript">

        $(function () {

            $(document).ajaxError(function (e, xhr, settings, exception) {
                console.log(xhr.status);
            });

            $('.trigger').click(function () {
                $('.result').load('ajax/thisUrlDoesNotExist.html');
            });

        });

    </script>
  </body>
</html>

What's your full page look like?

AndrewDotHay
Like a thousand lines of hell.
Andrew
+1  A: 

ajaxError is triggered when the actual XHR does not receive an HTTP success code from a given response from the server, as you can see in the jQuery source. The response codes in that particular function are perceived as "success" codes; anything else is a failure.

jQuery also only branches to the code that triggers ajaxError when your XMLHTTPRequest winds up with a readyState of 4 (complete with all data received), so I think shutting off your network connection would actually put you in a different XHR condition altogether (possibly a loop of condition 2?). You can see how jQuery branches in the source, too.

Basically, it looks if the server doesn't say the request failed and send back a code outside of that range above, you likely won't see ajaxError being triggered as, according to jQuery, it hasn't received an error.

ajm
Ahh, so it has to actually get data, and then it looks at the response code to see if there was an HTTP error?
Andrew
Yes. It examines the XMLHTTPRequest Object directly.
ajm