1

I have a .json file that changes every 10 seconds.

When a user of the website load the page, the code first loads the current .json file; then, the .json file is decoded into an array; and finally, it displays the data from that .json file and some other data based on .json file calculated by php (i.e. the sum of two data points of the .json file).

How could the page access to the "updated" json file and change the displayed data without reloading the page?

Thanks.

Javi
  • 170
  • 3
  • 13
  • You need to _poll_ the file using AJAX and JavaScript. – Tom May 31 '17 at 10:50
  • You have to use jquery Ajax . http://api.jquery.com/jquery.ajax/ – Aman Kumar May 31 '17 at 10:50
  • Don't know what it means to poll the file... – Javi May 31 '17 at 10:51
  • Wrap your code inside a function and use setInterval to call it again and again:-https://stackoverflow.com/a/3138784/4248328 – Alive to die - Anant May 31 '17 at 10:52
  • You need to make a Ajax call using jquery or angular js...jquery using $.ajax({}); or $http service calling using angular js – Deepa May 31 '17 at 10:52
  • https://stackoverflow.com/questions/19758954/get-data-from-json-file-with-php This link contains the information that how to access the json file using php. You can send ajax call to the php function which read the file and echo'ed the data. – kishor10d May 31 '17 at 10:53

1 Answers1

1

Since JavaScript is the only way to run code client-side, that's what you will have to use here. The basics of it is that you'll have to write some JavaScript to check the server every 10 minutes (for example), and update the page being displayed accordingly.

With jQuery, it'd look something like this:

function updatePage() {
    $.getJSON('/path/to/your/json_endpoint.json', function(data) {
        // Your code to update the page here.
        // `data` is the response JSON, in JavaScript object form.
    });
}

setInterval(updatePage, 1000 * 60 * 10);

Of course it can also be done with vanilla JavaScript, although it is a bit more complicated.

obskyr
  • 1,380
  • 1
  • 9
  • 25