MID
MID

Reputation: 1825

Is it possible to change json value in file using jQuery?

I want to make counter, which value will be the same for all users.

I have json file, which contains data: count = 0.

I want to run function every second which will be doing next:

1.Get value from json file

2.Update counter value

3.Change value in json file

4.Go to 1

Here is what I have now:

var counter = 0;
var myCounter = new flipCounter('counter', {value:counter});//initializing counter
 window.setInterval(function(){
$.getJSON('http://127.0.0.1:3000/counter.json', function(data) {1.taking the data from file
 myCounter.setValue(data.count);//2.Updating counter
 //3.here I need to change value from json file
})
}, 1000);

Can someone help me with point 3( How to change json value from jQuery ) ?

Upvotes: 2

Views: 3465

Answers (2)

Mike Brant
Mike Brant

Reputation: 71424

You would need some server-side script to modify the json file for you. You would just hit the script with ajax call and it could update the counter (in file or DB) for you. You don't want to set the "common" counter values at the client.

You would need the client to do nothing more than pull an updated count from the server (the server having incremented that count by one when receiving your request). If you expect alot of traffic, you probably don't want that counter in a flat file, but rather a database or in-memory cache.

Upvotes: 2

Brad Christie
Brad Christie

Reputation: 101614

Changes need to be made on-server. If you expect the server's record to update, the server needs to do it (albeit using $.post or $.postJSON) but you need to:

  1. Grab the value to the client
  2. Client makes update
  3. Client re-submits changed value to server
  4. Server updates value.

And unless you have logic on the server (i.e. counter.json isn't just literally a file with a number on it, but has server-side logic [like ASP, PHP, etc.]) you're not going to get too far.

To eliminate a round trip you could have the server update the count every time it's pinged though. Something like (on server):

  1. Grab the current count
  2. Increase counter by one
  3. Re-save new count
  4. Output count to client (where JavaScript now has the value)

Upvotes: 1

Related Questions