How to stop IE from caching AJAX requests
While working on an AJAX project over the weekend, I ran into the following issue: (through a GET request), every time I tried to call a certain function, It was returning the same data (which was supposed to be different each time)
I first tried the following (which should disable browser caching):
(in PHP)
header( “Expires: Mon, 26 Jul 1997 05:00:00 GMT” );
header( “Last-Modified: ” . gmdate( “D, d M Y H:i:s” ) . ” GMT” );
header( “Cache-Control: no-cache, must-revalidate” );
header( “Pragma: no-cache” );
The data still did not change.
I finally came to the following solutions:
1) use a POST request. When using with xmlhttprequest, it is slightly more complicated.
2) add a unique identifier to the end of my GET url.
I choose #2. A unique Identifier can be created using the current data+time. Here is a simple way to generate this (in Javascript):
var date = new Date();
var timestamp = date.getTime();
createXMLHttpRequest();
xmlHttp.onreadystatechange = handleMessages;
xmlHttp.open(”GET”,”script.php?time=”+timestamp,true);
xmlHttp.send(null);
5 comments
Try these headers instead-
header( “Last-Modified: †. gmdate( “D, d M y H:i:s Tâ€, time() + 3600));
By putting this a little bit in the future you can make up for the fact that some people’s clocks aren’t synced with yours. Alternatively, you could simply remove this header altogether, as without a validation most systems won’t cache.
header( “Cache-Control: no-cache, must-revalidate, no-store, max-age=0†);
An important note on Cache-Control- the “no-cache” attribute just tells the client not to give out the content without checking back with the server, while the “no-store” attribute tells the client not to even bother storing the content at all.
This website is a great resource for this- http://www.mnot.net/cache_docs
One final note- sometimes apache will add additional headers. You may want to use something like the firefox “liveheaders” plugin to see what your server is sending back.
You could also use POST instead of GET as IE doesn’t cache that.
Somewhat related, IE will use a cached request if POSTing with a Content-Length of 0 — a POST with no data. We had a case where a GET and POST were made on the same URL. IE would use the cached, GET response for a POST request, when no data accompanied the request. Cache-Control header to the rescue.
As for a client-side GET solution, using a header:
xmlHttp = createXMLHttpRequest();
xmlHttp.onreadystatechange = handleMessages;
xmlHttp.open(â€GETâ€,â€script.php?”,true);
xmlHttp.setRequestHeader(”Cache-Control”,”no-cache, private, max-age=0″);
xmlHttp.send(null);
In 2nd solution, you could’ve simply used Math.random() to generate a unique identifier.
[...] How to stop IE from caching AJAX requests [...]
Leave a Comment