I am very new to JavaScript and trying to display the latest values from a .json file, that keeps getting updated every 10 seconds, into a HTML page. I am reading the file every 10 seconds as well, but I am not getting the latest values from the file. I am getting values which are 50 to 60 seconds older.
I have tried disabling the browser cahche in chrome but still the same issue. Can somebody please help on this?
My JavaScript code to read the json file is as follows:
function readJsonFile(callback) {
var request = new XMLHttpRequest();
request.open('GET', 'http://localhost:8080/PersonalProject/filename.json');
request.onload = function() {
if(request.status>=100 && request.status<=100) {
//perform some operation
callback(request.responseText);
}
else{
//perform some operation
callback('FAILED');
}
};
request.onerror = function() {
console.error('Connection error');
};
request.send();
}
setInterval(function(){
readJsonFile(function(stat){
console.log(stat);
});
}, 10000);
You can add a timestamp as a parameter in your request to avoid the navigator cache:
...
let ms = Date.now();
request.open('GET', 'http://localhost:8080/PersonalProject/filename.json?ms' + ms);
...
I do that any time i need to update js and css files when requested from the html header and it works