sathishkraj
sathishkraj

Reputation: 43

Reload JSON file using jQuery on page refresh

What I am trying to do here is this:

$.getJSON(sampleJson.json), function(data) {}

Read data from sampleJson.json display on webpage. The displayed data is changed on a webpage submitted through an AJAX call as below:

$.ajax({type: "GET", url: "...", data: "abc" ,
    Success: function(data) {}

The data is taken to server side where I used servlet to get data. Here lies the problem, I write the data in the same sampleJson.json so the json file is updated. Now I want the changed data to get reflected on webpage on a page refresh since I am using the same sampleJson.json for display data on page load, but the webpage is not displaying the changed data.

I hope the problem is clear, is there a way to solve this issue?

Upvotes: 4

Views: 1480

Answers (2)

Dirk Vermeer
Dirk Vermeer

Reputation: 378

If you can modify the serverside serving the json file, then you can add 'no-cache' the header.

Doing this in nodejs-expressjs

..
res.setHeader('Cache-Control', 'no-cache');
res.json(yourdata);
..

but the how will depend on your serverside tech and the possibility to change it. (java?)

Upvotes: 0

Thanga
Thanga

Reputation: 8111

This is because the cached content is supplied from the second request. Add a timestamp parameter with the json url that will make the http request a fresh one everytime you request .. Like below

 var curTimeStamp = Math.floor(Date.now() / 1000);
 $.ajax({type: "GET", url: "/json/sampleJson.json?t="+curTimeStamp, data: "abc" ,
Success: function(data) {}

Upvotes: 1

Related Questions