views:

685

answers:

5

How to prevent browsers from caching Ajax results? I have and event triggered Ajax script the displays results only when the browsers data has been cleared.

Tested in IE6 and Firefox 3.0.10

+5  A: 

Add a random query string to the URL you are sending.

E.g. if the Ajax request is sent to "http://www.xyz.com/a" then add a random string at the end: "http://www.xyz.com/a?q=39058459ieutm39"

Itay
...and you can generate the random string in javascript for example like this: Math.floor(Math.random() * 1000000)
Manne
+2  A: 

There are two techniques for this that I'm aware of.

  • Add some sort of query string to the AJAX request URL so that it's always unique. A millisecond timestamp (perhaps combined with a random value) is good for this
  • Set HTTP cache control headers on the AJAX response so that the browser doesn't cache it
John Topley
+5  A: 

The random URL works, but it's kind of a hack. HTTP has solutions built in that should work. Try using the solution indicated here. Basically, set the headers:

"Pragma":            "no-cache",
"Cache-Control":     "no-store, no-cache, must-revalidate, post-check=0, pre-check=0",
"Expires":           0,
"Last-Modified":     new Date(0), // January 1, 1970
"If-Modified-Since": new Date(0)
Matthew Flaschen
Perfect, thank you.(Though it seems strange that the headers are set on the client rather than in the response from the server!)
David Underhill
+2  A: 

using jQuery you can set global ajax setting: { cache: false }. See it in jquery ajax docs

glaz666
A: 

I've used the jQuery {cache: false} method and it worked like a charm.

The complete code example is like this:

$.ajaxSetup({cache: false});
Mitch Labrador