Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax cannot cache

Tags:

ajax

php

caching

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.')';
like image 308
Yee Avatar asked Nov 03 '22 12:11

Yee


1 Answers

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.

like image 125
Mitch Satchwell Avatar answered Nov 11 '22 09:11

Mitch Satchwell