Yee
Yee

Reputation: 51

Ajax cannot cache

I want to cache the data in broswer so that broswer don't need to query the server in several minutes. I added php cache header but seems it doesn't work. Here is my ajax code and php code: Ajax code:

function myAjax(name, callback) {
    var url = './php/getJson.php?name=' + encodeURIComponent(name) + '&callback=?';
    jQuery.getJSON(url, function(data) {
        callback(data);
        jQuery.ajaxSetup({ cache: true });
    });
}

PHP code:

$seconds_to_cache = 3600;
$ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
$lm = gmdate("D, d M Y H:i:s", time() - $seconds_to_cache/2) . " GMT";
header("Last-Modified: $lm");
header("Expires: $ts");
header("Pragma: cache");
header("Cache-Control: public, max-age=$seconds_to_cache");

include_once('getData.php');

$output = $_GET['name'];

echo $_GET['callback'].'('.$output.')';

Thanks for MitchS and lenzai's help. This issue is solved. The cache:true option should be set before any ajax querying and old jquery libraries don't support caching. So make sure you are using the newest jquery library

For people who want a working example:

Ajax code:

var callback = function(data) {
    alert("callback");
}
function myAjax(name) {
    var url = './php/getJson.php?name=' + encodeURIComponent(name) + '&callback=?';

    jQuery.ajaxSetup({ cache: true });
    jQuery.getJSON(url, function(data) {
        callback(data);
    });
}

PHP code:

$seconds_to_cache = 3600;
$ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
$lm = gmdate("D, d M Y H:i:s", time() - $seconds_to_cache/2) . " GMT";
header("Last-Modified: $lm");
header("Expires: $ts");
header("Pragma: cache");
header("Cache-Control: public, max-age=$seconds_to_cache");

$output = '{"eventList":["event1","test event"]}';

echo $_GET['callback'].'('.$output.')';

Upvotes: 5

Views: 512

Answers (2)

Frederic Bazin
Frederic Bazin

Reputation: 1529

I wrote a test project adapted from your on your code. http://test-lenzai.rhcloud.com/index.html

Each time you press the button, it launches a new ajax request... The query is sent twice then the browser cache is used!!!!

This is caused by JQuery :

  • the first query is appended &_=s135227990... ( some timestamp probably)
  • subsequent queries don't have this extra argument and all identical queries are effectively using cache.

Now the question is how to tweak jquery so that 1st and second ajax queries are identical

Upvotes: 0

Mitch Satchwell
Mitch Satchwell

Reputation: 4830

You are setting the Last-Modified header to an hour ago and setting the max-age to be an hour.

This means at the point you send this data, it is already at the maximum age allowed for a cache and any subsequent requests must be resent.

Upvotes: 2

Related Questions