Well, I'm not going to write your script for you. I've given you enough, now it is the learners turn to look in the manual and read up on the functions (or functions alluded to (like locking)) and come up with some code. Everything is really laid out in the manual (including examples).
And by locking the file, you can actually use it to your advantage. You can "stall" the page until it can read the file. Then, the page isn't submitted 4 times or whatever. And, since you're only getting the contents (which is extremely fast) it really shouldn't be an issue.
Now, in saying that, there are issues. Like, if you have 3 people submit at once. First person reads 999 (so their the 1000th), second person reads 999, third person reads 999. So how do we combat this? Before writing, you get the contents again and write them to the file.
Here are the functions you need:
[man]fopen/man
[man]fclose/man <-- Automatically unlocks file(s)
[man]file_get_contents/man <-- Optional
[man]fread/man
[man]flock/man <-- Locks & unlocks files
As for the JavaScript, I'm not sure. I don't do javascript.