I have some JavaScript that sends an XMLHttpRequest()
to a PHP file every minute to fetch some JSON data, and then display it.
The first time this runs, after 1 minute, I get the "Success!" in the browser Console, and a request was made to /data.php
in the Network tab.
But subsequent times, I get "Success!", but with the same data (including the same time), and the Network tab shows no further requests were made to /data.php
const url = "/data.php";
setInterval(refreshData, 60000);
var refreshData = function () {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
// Only run if the request is complete
if (xhr.readyState !== 4) return
if (xhr.status >= 200 && xhr.status < 300) {
console.log("Success!", xhr);
displayData(JSON.parse(xhr["responseText"]));
} else {
console.error("Error fetching data");
}
};
xhr.open("GET", url);
xhr.send();
};
Here's data.php
:
header('Content-type: application/json;charset=utf-8');
$data = array(
"foo" => "bar",
"time" => time(),
);
echo json_encode($data);
I can solve this by adding a cache-busting "?" + new Date().getTime()
to the url
called by the JS.
Or by doing this in the PHP:
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
So I could use one of those solutions, but they smell a bit bad. I've tried this:
$seconds_to_cache = 1;
header("Cache-Control: max-age=$seconds_to_cache");
header("Pragma: cache");
$expire_time = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
header("Expires: $expire_time");
but it doesn't have any effect. What am I missing?