Debugging Why Your AJAX Requests Aren’t Working

AJAX is a great way to improve usability for a site or application and, with the up-rise of libraries such as jQuery, MooTools and Prototype, it’s never been easier to implement AJAX functionality.

When it’s working it can make tasks quicker to complete, and also means that the load on the server is reduced since only the required components are loaded. When it’s not working however, AJAX can be a little tricky to debug and find the root of the issue. This guide hopes to remove this difficulty by explaining a couple of ways to debug your AJAX requests.

Use of the library functions

If you’re using a JavaScript library, such as jQuery, to assist with performing AJAX requests, you’ll find that they come with a few handy functions to assist with code that’s not working as expected.

Sticking with jQuery, a couple of examples of using the available functions are as follows:

Global AJAX error handler
jQuery comes with a global function, ajaxError(), that gets executed each time any AJAX errors occur within the entire page. An example of this is as follows:

As good practice, it’s wise to get into the habit of always using these error handlers. They shouldn’t be used just when debugging something, but all the time in the event that your users experience an issue with the request.

The above works but only in the case that an error with the actual request occurs, for example an invalid URL, a server error or if the request times out.

Sometimes a request might be absolutely fine, but it’s the data sent and/or received that’s causing the uncertainty. Being AJAX, the data sent and received is almost invisible from the front end so we need to use some special tools to see what’s going on behind the scenes.

Using developer tools

Most modern browsers come equipped with some sort of developer tools. Alternatively there are third-party add-ons, such as Firebug, which can also assist us. You can normally access these developer tools by pressing F12 on the keyboard.

In summary, what these tools allow us to do is view all the traffic between the browser and the website, including each request, the headers sent, and more importantly the response.

Below I’m using the developer tools that comes with Chrome. What you can see here by switching to the ‘Network‘ tab is some AJAX requests that have been made.

Clicking one of the requests will then show you more information. Here I’ve clicked one of the AJAX requests and can see all of the headers sent:

So there we have it. Two useful methods to help you figure out why your AJAX requests aren’t working as expected, and assist with getting a view on what’s going on behind the scenes.