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.

About the author

Jesse Skinner Hi, I'm Jesse Skinner. I'm a self-employed web developer with over two decades of experience. I love learning new things, finding ways to improve, and sharing what I've learned with others. I love to hear from my readers, so please get in touch!