AJAX Tips and Tricks

By Kris Hadlock

Date: Nov 17, 2006

Article is provided courtesy of Sams.

Return to the article


If you're developing in AJAX, author Kris Hadlock has a few tricks you can use to avoid common issues and speed up your AJAX development time. This article shows you how to prevent cached AJAX requests, debug AJAX code with FireBug, and create a database connection.

This article shows you a few tricks to avoid common issues and speed up your AJAX development time. Many such timesavers are already in use; when you have a specific need, it’s worthwhile to research what has already been tried.

First, we’ll cover how to make sure that your AJAX requests are not cached by the browser. Next, we’ll explore a great tool for debugging AJAX applications in Firefox. Finally, I’ll show you a basic database-connection tip for responding to an AJAX request with valid XML from the server.

Let’s get started.

Preventing Cached AJAX Requests

As a developer, you’re probably well aware of all the issues that commonly occur due to cached data. AJAX is not unique when it comes to these issues; in fact, this problem is fairly common. Luckily, there are workarounds, one of which involves JavaScript’s Date object. If you haven’t used this approach for other caching issues, you’ll be pleasantly surprised at how easy it is to implement.

When making a standard HTTP request, the browser caches the web pages that we visit. Query strings are one way to work around this behavior. Therefore, we could easily use a query to our advantage by adding a simple query at the end of an AJAX request. But this will solve only half of the problem—if the query is the same each time, the data can still be cached. Therefore, we need to create a unique query each time a request is made. There are many ways to handle this need, but the one that makes the most sense in this situation is to use time to our advantage—because time is always changing.

The example in Listing 1 takes a uri parameter that will be used to make the request. Once we create the appropriate request object, we then create an instance of the Date object that will be used to create the next variable, called uniqueURI. The uniqueURI starts with the uri parameter; then we use a condition that checks for the index of a question mark, which would symbolize an existing query string. If the query string exists, we simply append an ampersand to the query; otherwise, we append the question mark. For either condition, the uri is followed by a key/value pair of "timestamp=" plus the current time from the Date object. Once we have the uniqueURI, we’re ready to finish making the request.

Listing 1 Creating a Unique URI

function xmlLoader(uri) 
{
  var request;
  if(window.XMLHttpRequest)
  {
    request = new XMLHttpRequest();
  }
  else if(window.ActiveXObject)
  {
    request = new ActiveXObject("MSXML2.XMLHTTP");
  }
  var timestamp = new Date();
  var uniqueURI = uri+ (uri.indexOf("?") > 0 ? "&" : "?")+ "timestamp="+ timestamp.getTime();
  request.onreadystatechange = callbackMethod;
  request.open("GET", uniqueURI, true);
  request.send(null);
}

The uniqueURI variable is all it takes to avoid cached requests with AJAX.

Now let’s take a look at how to debug our code.

Debugging AJAX Code with FireBug

JavaScript has always been an extremely difficult language to debug, due to the fact that it’s loosely typed and no good tools have been available. Therefore, it’s equally difficult to debug AJAX, because the requests and the responses are all handled by JavaScript. Luckily, Joe Hewitt’s FireBug extension for Firefox is extremely useful for debugging JavaScript and AJAX requests/responses. In this section, I’ll show a few of the features that FireBug offers to help you debug not only JavaScript, but any AJAX requests you make.

The Console tab in FireBug is where all AJAX requests, errors, and warnings appear (depending on the preferences you’ve set). Figure 1 shows the options that you can choose to display in the console; the checked items are active. Once you’ve configured the options the way you like, messages display in the console for those options when they occur.

Figure 01

Figure 1 Options in the FireBug console.

The console also allows you to type JavaScript code into the command line at the bottom of the window for testing. Figure 2 shows an example.

Figure 2

Figure 2 Testing code in the console.

FireBug allows you to inspect the DOM while rolling over elements in the page. This feature can be extremely useful for debugging the nesting sequences of the page for CSS and JavaScript code. With AJAX, it can be useful when you’re adding elements to the page dynamically and need to check their placement.

The debug feature is unbelievable, as it allows you to view all of the JavaScript files that are used in the page (see Figure 3) and set breakpoints in the code just as you would in more sophisticated programming tools (see Figure 4). These features are important because they can save a lot of time in debugging code and finding the exact line of code that’s causing a specific issue.

Figure 3

Figure 3 Viewing each JavaScript file in a web page.

Figure 4

Figure 4 Testing JavaScript with breakpoints.

The most relevant part of the FireBug tool in terms of AJAX is the option to show XML HTTP requests. This feature allows you to view all requests made on the Web. You can see whether this feature is active by clicking the Console tab, opening the Options menu, and making sure that the Show XMLHttpRequests option is checked. Once it’s working, you’ll see all XML HTTP requests that are made (see Figure 5).

Figure 5

Figure 5 Viewing XML HTTP requests with FireBug.

In addition to seeing the request that was made, you can view the response (see Figure 6) and the headers (see Figure 7). Seeing the response is extremely useful because you can view all the server’s responses, before you even begin to parse the data and deal with it in JavaScript. This means no more JavaScript alerts on the responseText property from the request object. Viewing the headers is extremely useful because you can get information from the server, such as when the requested file was last updated, what type of server it’s on, and so forth.

Figure 6

Figure 6 Viewing the response for an AJAX request.

Figure 71

Figure 7 Getting server information from the response headers.

Now that we have some ways to debug, let’s take a look at creating database connections with AJAX.

Creating a Database Connection

Every developer should be aware of the following trick when creating a database connection with AJAX and PHP. When responding with XML data from the server, PHP’s header method allows you to set the Content-Type of the file, which needs to be application/xml. The following line of code simply constructs an XML file with strings and writes them to the page via PHP:

header("Content-Type: application/xml; charset=UTF-8");

Without this line of code, the response may not be seen as valid XML, which will break your request.

I hope that these tips and tricks save you some time when developing AJAX-enabled applications. They’ve helped me in numerous situations.