Wednesday, April 25, 2007

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.

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.

No comments: