AJAX Force Refresh

Hello, I was working on a small AJAX application and I’m having problems because the browser is caching the pages and I can’t find a way to force the browser to request the page again. In my page, I load fetched documents into a div to display to the user, but when I modify the file on the server, the changes aren’t being sent to me. Is there anyway that I can force the browser (in my case firefox) to get the latest page from the server, something like a force-refresh feature? Thanks a lot.

to get rid of cache you need to set cache headers using a server-side language.

I figured something like that would solve it, but is there anyway to do it from javascript?

ummm… window.location = same_page;

I had a similar problem, to fix it I sent an extra value in the query string to ensure fresh content everytime.

var rand = Math.random(9999);

and then just attach “rand” to the end of your query string.

The simpliest thing I’ve found that works in both IE and Firefox is to send a last modified header with the xml response. In php in you’d send something like this:

header('Last-Modified: '.date('D, d M Y H:i:s', time()).' GMT');

You can either play with the headers being sent FROM the server, or you can change the request TO the server (to something which hasn’t been sent before and therefore cannot have been cached). Like diz, I prefer doing this kind of thing locally in JS rather than messing with PHP headers. Though instead, I’d rather not work with basic random strings.

function NoCache(url) {
  return new String(url + (new Date().getTime()));
var url = NoCache('http://example.org/ajax.php?nocache=');

Since the Date.getTime returns the number of milliseconds (1/1000 seconds) since Jan 1 1970 we can reliably assume that each new request (assuming there is more than a millisecond between requests!) building afrom NoCache each time, will be to a different url. So, the server will see “…ajax.php?nocache=1137326593589” (for example) and spit out the page. Now when you update “url” with NoCache a few seconds later you’ll request (again, for example) “…ajax.php?nocache=1137326719090” which the server will assume is an entirely new page (well, it is!) and the browser will have never seen it before so will have no local cache.