David Smith
David Smith

Reputation: 147

Ajax cache not working for some reason

I am having problems understanding why and how my ajax requests are not being cached.

I've read up on about 50-60 different articles on the web that say this should work.

$.ajax({ 
  type: "GET",
  cache: true,
  url: 'get.php',
});

but when I look in firebug or developer net tab. I keep seeing the page being loaded with a 200 response code which means it is loading a fresh new page instead of an older cached.

So to make the test even more basic, I added a blank separate page purely display a datetime, so I can see if it is being cached or not.

It did not work, datetime was still being updated.

So next I tried to set the headers like this on get.php:

$cache_length=600;

header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + 3600));
header("Pragma: cache");
header("Cache-Control: max-age=$cache_length");
header("User-Cache-Control: max-age=$cache_length");
echo date('Y-m-d H:i:s');

That still doesn't cache it.

Then I tried this:

$.ajax({ 
  type: "GET",
  cache: true,
  url: 'get.php',
});

Still the same problem, no caching taking place

Then I also tried this, still no caching

$.ajaxSetup({ cache: true }); $.ajax({ type: "GET", cache: true, url: 'get.php', });

Then I tried this, still no caching

$.ajaxSetup({ cache: true });
$.ajax({ 
  type: "GET",
  cache: true,
  url: 'get.php',
});

So I am baffled why it won't cache it, when examples online seem to make it pretty simple to cache it by specifying cache:true.

No matter what i try, I am still seeing an updated time in get.php, make me believe that cache is still not working, but don't understand know why

How do I cache the page for one hour?

Upvotes: 1

Views: 965

Answers (1)

Jason Roman
Jason Roman

Reputation: 8276

I think you are misunderstanding how the cache variable works. The default value for cache is true, so you don't even have to set it. It doesn't actually tell your browser or computer or server to cache anything. The main purpose of the variable is to be able to set it to false so it forces the browser to not cache the page by way of adding "_={timestamp}" to the GET parameters.

Further explanation: http://api.jquery.com/jquery.ajax/

Keeping the value at true simply means the response will behave like any other page.

Upvotes: 2

Related Questions