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:
value = ( timestamp % ((max_limit - min_limit) / 1.5 ) ) * 1.5 + min_limit
I'm not entirely sure how your counter is going to work - where it's counting from etc, but I think this should help you:
var init_count = 10000100260; //starting heartbeats
var count_start = 1325803921; //timestamp of when initial count was taken
function update_count()
{
var utstamp = new Date();
utstamp = Math.round(utstamp.getTime()/1000); //get current unix timestamp
var newcount = (utstamp - count_start) + init_count; //add seconds passed since initial count, to the initial count
$("#beat_count").html(newcount); //set the contents of your element to the new number
}
var ticker = setInterval(update_count,1000); //call the above function every 1000 milliseconds (1 second)
You can get your initial timestamp by using the form here: http://www.functions-online.com/mktime.html
This could raise more questions than it answers, but let me know either way!
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.
I assume you're having multiple browsers running per user. The counter works, but what you think is a user is infact a browser. As every browser will trigger the increase of the count, what you describe is not a problem but just the fact how your script works.
Related
I need help creating a counter that starts from 1 value (2000000) and ends at 2nd value (2500000), resets every day and does not restart upon page load.
I was able to get almost exactly what I want with javascript - but this restarts on page load/refresh. I imagine I need to write this in PHP, but I can't figure out how - any help/pointers would be awesome.
Here is the javascript example on JSfiddle and below:
var start = 200000001;
var end = 250000000;
var interval = 578;
var refreshIntervalId = setInterval(function(){
if(start <= end){
$("#start").text(start++);
}else{
stop();
}
},interval);
function stop(){
clearInterval(refreshIntervalId);
}
it's possible to solve you problem with ajax function and get the value from a database.
if you want use Cronjob and php for your probelm and dont work with database , use text file .
save your current number in a text file , i write a function for you a sample below :
function yourfunction($start,$end){
$perv = file_get_contents("num.txt");
if($perv <= $end){
$current = $perv++;
file_put_contents("num.txt","$current");
}
}
I would like to make a while loop which executes and echos out the values between 1 and 90, each being 1 second apart. However, instead of them all being written in a row, I'd just like it to increase the one echoed value, if that makes sense. It's supposed to be for a football game and is basically a timer. I am not too sure on how to do it so any assistance would be greatly appreciated!
Thanks!
You will hang the PHP engine for a minute and a half if you use PHP for the counter. The result that is shown to the user is a page with the number 90 that took 90 seconds to load. What you need is javascript to increase the values of a text span after a second.
In PHP, echo just the first number, and use JS to increment every second.
<?php
echo '<head>
<script type="text/javascript">
function advance() {
var txt = parseInt(document.getElementById("timertext").innerHTML);
document.getElementById("timertext").innerHTML = txt + 1;
if(txt != 89) {
setTimeout("advance()", 1000);
}
}
</script>
<head>
<body onload="advance()">
<span id="timertext">1</span>
</body>';
?>
Ok , I'm having trouble to solve this , I'm a php / C# web developer , and have no experience or knowledge in Javascript, I have to do just this one thing that needs Javascript:
When a certain page loads, a counter starts. The client must stay on this page for 20 seconds. after, I want to execute php code.
So there are 2 issues concerning me, first: how do I stop the counter, if client leaves the page (meaning the page is not in focus).
2) How can I execute php in javascript? , or call a php function from Javascript.
The code I have so far is this:
<html>
<head>
</head>
<body>
<div id='timer'>
<script type="text/javascript">
COUNTER_START = 20
function tick () {
if (document.getElementById ('counter').firstChild.data > 0) {
document.getElementById ('counter').firstChild.data = document.getElementById ('counter').firstChild.data - 1
setTimeout ('tick()', 1000)
} else {
document.getElementById ('counter').firstChild.data = 'done'
}
}
if (document.getElementById) onload = function () {
var t = document.createTextNode (COUNTER_START)
var p = document.createElement ('P')
p.appendChild (t)
p.setAttribute ('id', 'counter')
var body = document.getElementsByTagName ('BODY')[0]
var firstChild = body.getElementsByTagName ('*')[0]
body.insertBefore (p, firstChild)
tick()
}
</script>
</div>
</body>
</html>
and I also want the timer to start ticking when the client gets back on page
Thank you very much for ur help in advance
You could do this using jQuery.
Recycling an old Stackoverflow post, try this:
var window_focus;
var counter = 1000;
// on focus, set window_focus = true.
$(window).focus(function() {
window_focus = true;
});
// when the window loses focus, set window_focus to false
$(window).focusout(function() {
window_focus = false;
});
// this is set to the ('click' function, but you could start the interval/timer in a jQuery.ready function: http://api.jquery.com/ready/
$(document).one('click',function() {
// Run this function every second. Decrement counter if window_focus is true.
setInterval(function() {
$('body').append('Count: ' + counter + '<br>');
if(window_focus) { counter = counter-1; }
}, 1000);
});
Demo and old post
DEMO | Old So post
Update
Probably because the demo runs in 4 iframes, the $(window).focus bit only works on the iframe actually running the code (the bottom-right window).
jQuery
jQuery.com (How jQuery works) | Example (back to basics halfway down the page) | If you use the 2nd link, also read this
In regards to your first question about detecting if the window is out of focus, see this answer: Is there a way to detect if a browser window is not currently active?
It is possible, but only very new browsers support this so it may not be useful based on current browser support.
To trigger PHP code from Javascript, you would have to make an AJAX call to a server-side PHP script to invoke PHP since JS is client-side and PHP is server-side.
I'm trying to update my database with some information. One of the key pieces of information is how much time has passed since the page first loaded and when the user click a button. My code looks like this:
<script>
function pauseVideo() {
$.get("video_pause.php?pause=" + timePassed + "&videoid=<?php echo $_GET['sessionid']; ?>&sessionid=<?php echo $_GET['videoid']; ?>");
}
</script>
and
<html>
<div id="pause" onclick="pauseVideo()">PAUSE</div>
</html>
My PHP is fine so ignore that. The part I'm having trouble with is the 'timePassed'. I need this to be the amount of time in seconds since the page was first loaded and the person clicks the PAUSE div.
I think I need to run a function on click to find the passed time and then use that time variable in the $.get() somehow?
When the document loads, just save the current time in a variable:
$(document).ready(function() {
var timeWhenLoaded = (new Date).getTime() / 1000;
});
Then, when the pause button is clicked, calculate the time that has passed:
function pauseVideo() {
var currTime = (new Date).getTime() / 1000;
// time in seconds
var timePassed = Math.floor(currTime - timeWhenLoaded);
$.get("video_pause.php?pause=" + timePassed + "&videoid=<?php echo $_GET['sessionid']; ?>&sessionid=<?php echo $_GET['videoid']; ?>");
}
Get rid of the onclick in your HTML, and remove your existing function, then put this in the head section of your page:
(function(){
var loadTime = (new Date).getTime(); // Page started loading
$(function(){
// DOM fully loaded, so move the assignment here if that is what
// you want to consider as the load time
$('#pause').click(function(){
$.get("video_pause.php?pause=" + Math.floor(((new Date).getTime() - loadTime)/1000) + "&videoid=<?php echo $_GET['sessionid']; ?>&sessionid=<?php echo $_GET['videoid']; ?>");
});
});
})();
Also note that you can never trust that variable on the server side. Anyone could input a negative number or even the word 'pizza' for the value if they really want to.
Something like:
var startTime = (new Date).getTime() / 1000;
function pauseVideo() {
var curTime = (new Date).getTime() / 1000;
var timePassed = Math.floor(curTime - startTime);
$.get("video_pause.php?pause=" + timePassed + "&videoid=<?php echo $_GET['sessionid']; ?>&sessionid=<?php echo $_GET['videoid']; ?>");
}
if the page with the following code is generated server-side, you can either just pass the current time to the script, as in:
<html>
<div id="pause" onclick="pauseVideo('" + curTime +"')">PAUSE</div>
</html>
(needs echo syntax)
or put it in a hidden field and pass it back to the server. (and do your calculations in php)
this way, you get the time passed since the page was requested...
I'm using codeigniter and I have a timeout function using jquery. I just need to find a way to get a number (an int) from a field in the database the application is using and set the initial int in the javascript file to it. As you can see in the code '900000' needs to be dynamically received from a database table. Since it does not need ajax(does not need dynamically receive data in real time) I would like to find a lighter solution if possible. What would be the best practice in this situation?
$(document).ready(function () {
idleTimer = null;
logoutTimer = null;
idleWait = 900000; //15 minutes
logoutWait = 30000; //30 sec
timeUp = false;
Just use echo to output the value at that point in the script.
idleWait = <? echo $timeoutValueRetrievedFromDataBase ?>;
PHP will not run in your standard JS file without quite a bit of modification. First off, find the .php file where your <head> section is located. Find the first <script> tag, you will want to work before this. That way you can go ahead and set a variable that will be ready when your JS file gets loaded.
Right above your first <script> tag insert something like this
<script>
<?php
//you will need to connect to db here and get your timeout value from the database
//we assume $timeout has the correct value in it
echo "var phpTimeout = $timeout;"
?>
</script>
You would then go into the script you pasted into the question and do this
$(document).ready(function () {
idleTimer = null;
logoutTimer = null;
idleWait = phpTimeout; //this is the variable we set earlier in the <head> of the document
logoutWait = 30000; //30 sec
timeUp = false;