AJAX & IE Caching Issues

Missing Image
By Ken Foubert

I've been working on a project that involves using the jQuery javascript library and the Ajax methods. I've been happily using the Ajax jQuery.get() method to handle simple calls, such as a link that allows a user to view a list of words based on their selection, getting the contents of a tab when the user selects a tab, and finally getting the current weather after the person enters a new zip code, which is then saved to the database.

For the last operation, I got the JavaScript working great on Firefox and I thought it was working in Internet Explorer. However, after some testing, I noticed that the same weather data was being returned, even after a new zip code on the opposite coast was selected. Mmmm, I was rather baffled, especially since I've been using this jQuery.get() on the other functions, and encountered no problems like this.

So, I started the Visual Studio 2005 debugger and viewed the page in Internet Explorer. I stepped through each line of code, so far so good. Then I pressed the edit weather preferences button, the form popped up, I changed the zip code, pressed the save button, and stepped through each line of code again. The weather data was updated to the database correctly. Next, the form closed and the Ajax jQuert.get() method was called. The debugger should have gone to the page for returning the weather data, but that did not occur. Instead, the data from the very first Ajax call was returned. That could only mean one thing, the infamous caching issue, which can be the bane of web developers and dynamic content.

I quickly queried Google for "jquery ie caching get" and the very first entry, Ajax IE Caching Issues, had the solution. It turns out that, according to a comment from that article, the http specifications says any agent in the chain can cache the GET request, which Internet Explorer tends to do.

The solution is very simple, either use a POST request instead or add a parameter to the querystring that changes. Some ideas could be adding a timestamp to the end of the url, adding a flag that changes each time the weather data is returned.

Here's the original code that caused IE to cache the response. Notice how the url is always "ajax/weather.aspx?action=get", which causes IE to cache the response.

$.get("ajax/weather.aspx", { action: "get" } , function(data) { getUsersWeatherCallBackHandler( data ); } );

This code uses a timestamp to make the url unique each time the function is called.

var tsTimeStamp= new Date().getTime();

$.get("ajax/weather.aspx", { action: "get", time: tsTimeStamp} , function(data) { getUsersWeatherCallBackHandler( data ); } );

This code simply uses a post request instead to get around the caching problem.

$.post("ajax/weather.aspx", { action: "get" } , function(data) { getUsersWeatherCallBackHandler( data ); } );


Back To Feed