I have a JSON file on my server that gets updated every 5 minutes. However, when refreshing my site after an update to the JSON file, the data is cached and is not showing the latest data until I hard refresh.
How can I avoid this and ensure that the latest data set is being shown?
I have this in my header:
<meta http-equiv="Expires" CONTENT="0">
Here my function that gets run on page load:
let buildings = [];
async function getWG() {
let updated = await fetch('cron_log.txt');
updated = await updated.text();
let updateText = document.getElementById("updated");
updateText.innerHTML = '';
updateText.innerHTML = 'Updated: ' updated ' EST';
console.log(updated);
if(buildings.length < 1){
let response = await fetch('wg_data.json');
buildings = await response.json();
buildings.sort(function (a, b) {
return a.fee - b.fee;
});
}
//console.log(buildings);
let element = document.getElementById("mainData");
element.innerHTML = '';
//loop thru array of buildings
for (var x = 0; x < buildings.length; x ){
//document.write(buildings[x].community);
if(!buildings[x].closed){
let row = '<div ><div >' buildings[x].community '</div><div >' buildings[x].landId '</div><div >' buildings[x].type '</div><div >' (buildings[x].fee 1000) '</div><div >' buildings[x].rank '</div></div>';
element.innerHTML = row;
}
}
}
Here is my PHP file that gets called every 5 min and retrieves the latest data, then saves to the JSON file:
$curl = curl_init();
$url = test.com;
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
));
$response = curl_exec($curl);
$data = json_decode($response,true);
CodePudding user response:
From this:
let response = await fetch('wg_data.json');
buildings = await response.json();
it looks like you fetch a static file. You could configure your webserver to add a header to expire the data of this file immediately, which will tell the browser to not rely on its internal cache.
Alternatively, you can fool the browser to request a new file each time, thus avoiding using a local cache. Do that by creating a unique URL, such as:
let response = await fetch('wg_data.json?t=' new Date().valueOf());
buildings = await response.json();
which produces a new URL each time, such as 'wg_data.json?t=1672100283407'
. The server ignores the URL parameter, and just delivers the file.
You might need to do the same for fetch('cron_log.txt')
as well.
CodePudding user response:
//change this row: let response = await fetch('wg_data.json'); let response = await fetch('wg_data.php?rand=' Math.random());
add wg_data.php file into same folder.
wg_data.php :
<?php
header('Content-type: application/json');
echo file_get_contents('wg_data.json');