Preventing IE from caching Ajax requests

We are increasingly using AJAX (Asynchronous JavaScript and XML) to deliver content on our pages, but often have problems due to Internet Explorer, every web developers favourite browser, caching AJAX requests. This means that the results presented are not updated when a new request is made to the same URL, even if the data has changed.

This is annoying, but does not go against the HTTP specification, which states that GET requests are cacheable, whereas POST results are not. AJAX requests seem to generally default to GET (JQuery certainly does), so IE caches them.

Therefore, the solution is to make sure that AJAX requests use POST rather than GET. In jQuery, you can do this by setting:

type: 'POST'

For Prototype, you can set:

method: 'get'

In the jQuery.ajax() method, there is also a ‘cache’ setting, which is true by default, but can be set to false, which prevents caching. It does this by appending a TIMESTAMP to the URL, so that each request is made to a different URL, so a cached result cannot be returned. If not using jQuery, an alternative to ensuring that your request is a POST request rather a GET request is to add a ‘cache-busting’ parameter, e.g. a timestamp, to the end of the request URL, e.g.:

var cacheBuster = new Date().getTime();  //Get timestamp
var url  = 'http://www.example.com/getdata?cb=' + cacheBuster;  //Add timestamp to URL

2 Replies to “Preventing IE from caching Ajax requests”

  1. It’s worth mentioning that, as well as the ‘cache’ setting inside each ajax call, you can also disable ajax caching for JQuery globally with:

    $.ajaxSetup({ cache: false });

  2. This is a bad solution. You’re now using the “wrong” method for the given resource. This is a misuse of HTTP.

    Instead, you should configure your server to provide the proper cache-related Header values in its response for these resources.

    That’s fairly fundamental web application stuff!

Leave a Reply

Your email address will not be published. Required fields are marked *