2

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 ) ?

2
  • 1
    You will need some server-side script to modify the file for you. Do you have some server-side script? Commented Sep 13, 2012 at 15:05
  • So, you want to write to the counter.json file? If so, you won't be able to do that with just javascript. You will need some server-side language to handle that. So you could basically POST your updated json and have the server code use it to write to the json file. Commented Sep 13, 2012 at 15:05

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

my counter won't be counting users. It just will be running. Should I use db for this ?
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.