Steingrimur Jonsson Steingrimur Jonsson - 1 month ago 8
Javascript Question

How do I only refresh page when there is a change in the .JSON?

I need the browser only to reload when there is a change made in the 'Stockdata1.JSON' file. Hope someone can help.

$.getJSON('Stockdata1.json', function (data) {
datastr = JSON.stringify(data);
document.write(datastr);
setTimeout(function(){
window.location.reload(1);
}, 5000);
});

Answer Source

I would to it by string comparison, either by receiving the string and then parse it to an object, or by stringifying.. I go with the latter, because of the above snippet:

var currentDataString;
$.getJSON('stockdata1.json', function(data) {
  var resultAsString = JSON.stringify(data);
  if (!currentDataString) currentDataString = resultAsString;

  if (currentDataString !== resultAsString) {
    window.location.reload(1);
  }
})

Attention

I see a misconception here.

In the time you reloading, the data could change again, this would mean you would miss one tick.

Further toughs

Like Rickard mentioned, it's possible to update the DOM dynamically if all you need is inside the JSON. You don't have to reload the whole world to plant a tree.

Based on your needs, you could just update the tables, where you want to show the changes, it's also not very user-friendly if the whole page is suddenly reloading.

Obviously this would require some deeper knowledge of JS and the DOM, but it's not difficult at all, and after all at some point you need this knowledge anyway.