Coding with Jesse

Hidden Ajax Errors with jQuery

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.

Published on July 4th, 2007. © Jesse Skinner

About the author

Jesse Skinner

Hi, I'm Jesse Skinner. I'm a web development coach & consultant. I teach web development teams how to scale up their server infrastructure, improve automated testing and monitoring, reduce costs, and modernize their legacy systems. I focus on empowering teams through customized training and coaching.

Feel free to email me. I'm eager to hear about your challenges and see how I can make your life easier.