I have a strange problem and I wasn’t sure how to word the title.
What I’m Trying To Do:
I want to keep track of a running total and I want this running total to update live to my page every second. I’m not trying to track visitors, it’s going to track something weird like “amount of blood cells in your body right now!” Here is a website that does what I want to do, but they do it in jquery, I’m trying to do it in JS to keep the JS files to a minimum. http://www.usagain.com/ (left side)
How I’m Doing It:
I have a JS file with AJAX that is linked to a PHP file and that PHP file opens a Text file -> grabs a number -> increments it by 1 -> sends said number back to the JS -> Updates the number to HTML -> and the PHP updates the text file -> close txt file.
My Problem:
The counter works, it increments but the problem is if I have 2 browsers running the same page the number will increment by 2. If I have 3 browsers; the number will increment by 3 and so on. I think it has something to do with the writing to the file but I’m not sure how to fix it.
My Code
HTML/CSS/Javascript/AJAX
<html>
<head>
<title>Counter</title>
<script language="javascript" src="../jquery1.6.js"></script>
<script type="text/javascript">
function addCommas(nStr) //http://www.mredkj.com/javascript/nfbasic.html -- Source
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
function getNum()
{
$.post('test.php', function(data){
$('#counter').html(addCommas(data));
})
}
setTimeOut(getNum, 1000);
</script>
<style type="text/css">
#counterContainer{color: #52504D;font-family:Verdana, Geneva, sans-serif;font-weight:bold;font-size:15px;position:relative;top:22px;}
#counter{color: #1E7EC8; font-size: 25px;letter-spacing:1px;}
</style>
</head>
<body onload="getNum()">
<div id="counterContainer">
<div id="counter"><!--Counter Goes Here, Do Not Disturb--></div>
</div>
</body>
</html>
PHP File
<?php
$fp = fopen("staticNum.txt", "r+");
flock($fp, LOCK_EX);
$num = fgets($fp, 11);
$num = intval($num)+1;
echo $num;
fseek($fp, 0, SEEK_SET);
fputs($fp, "$num");
flock($fp, LOCK_UN);
fclose($fp);
?>
My Text File just has this number in it:
10000100260
Any suggestions would be great. My first thought was a database but then I figured I’d have the same problem. I do want to stay away from Session variables and Cookies though for sure since I don’t think they’re necessary. I could be wrong though.
Bonus points if you can figure out a way to solve my problem without a database! (Not really though im not an admin 🙁
Instead of counting, try with timestamp: