Coding with Jesse

Hidden Ajax Errors with jQuery

July 4th, 2007

If you use Ajax with jQuery, you may have noticed that you don't get any error messages when things go wrong. Even if you have major bugs in your callback functions, jQuery just silently fails, sweeping any errors under the rug, and leaving you clueless as to what just happened.

For example, you can do this and you won't get any errors:

$.get('page.html', function(){
    this_function_does_not_exist();
});

There are two ways to fix this. You can use $.ajax with the error parameter, passing an error handling function for that particular Ajax call. Or, you can define a global Ajax error handler. If you do a lot of Ajax, and you use Firebug, the latter is a great option. Try this:

$(document).ajaxError(function(){
    if (window.console && window.console.error) {
        console.error(arguments);
    }
});

After running this code, you'll start getting error messages in your Firebug console (if anything breaks with your Ajax calls or callbacks). The error messages aren't the greatest, but at least you don't have to stay in the dark any longer.


Interested in web development? Subscribe to my newsletter!

Comments

1 . Jörn Zaefferer at 2007-07-06T12:25:14.000Z

Jörn Zaefferer

That's a great tip. That generic error handler inside jQuery's ajax method can be quite annoying otherwise. I wonder if these two lines should go into jQuery core...

2 . Andy Cai at 2007-07-11T05:25:20.000Z

Andy Cai

like the jquery.

3 . jonnix at 2007-11-08T20:15:52.000Z

jonnix

Thank you very much. This tip helped me find an error I have been guessing for during 2 days.

4 . Acronyms at 2008-04-02T07:25:12.000Z

Acronyms

I used similar way, put creating a separate function.

5 . colin at 2008-05-08T21:42:06.000Z

colin

Thank you, this idea just saved me a lot of guess work

6 . Braden at 2008-05-14T23:55:04.000Z

Braden

I'm confused--this doesn't seem to work with 1.2.3. Did they at one point try { success() } catch() { handleError(); }? I know Dojo does that, but I don't see it in 1.2.3 or 1.0.0.

7 . Mat at 2008-07-27T14:00:50.000Z

Mat

Thanks for the tip :)

8 . Vlad at 2008-09-02T16:25:28.000Z

Vlad

Thank you!

9 . LaPeGa at 2008-11-26T19:51:54.000Z

LaPeGa

Thanxxx

10 . Ramiro at 2009-03-06T21:06:27.000Z

Ramiro

Great Tip!!! specially the debug to console using firebug. Thanks

11 . zoltantoth at 2009-05-10T20:59:34.000Z

zoltantoth

his is exactly what I was searching for. You could not explain it simplier.

Thank you.

P.s.:
I would draw your attention to the error in the comment engine:
If I use a single quote, you are double escape-ing it, so it throws an SQL error, so the shortened "could not" will not work.

12 . xxx at 2010-08-30T07:38:36.000Z

xxx

that was great tip - thanks