Creating a counter php - php

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>';
?>

Related

Counter between 2 values with Daily Reset

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");
}
}

Javascript countdown not working for php loop

Hello i me and a friend have a maffia game. I have a countdown timer code but it only works when i use one timer. But i need to use it in a loop to get more timers in a table. I searched on google but nothing really helped. I saw that i had to use different id's but that didn't work for me. I have little knowledge of javascript.
This are my codes:
While loop:
while($info = mysql_fetch_object($dbres))
{
$j = 0;
$bieding = mysql_fetch_object(mysql_query("SELECT `bedrag` FROM `biedingen` WHERE `veilingid`='{$info->id}' ORDER BY `bedrag` DESC LIMIT 1"));
$tijd = ($info->tijd + $info->duur * 60 * 60 - $time);
echo '<tr>
<td>'.veilingnaam($info->id,1,1).'</td>
<td>'.usernaam($info->veiler,1,1).'</td>
<td>€'.getal($bieding->bedrag).'</td>
<td><div id="teller'.$j.'"></div></td>
</tr>';
}
Javascript part:
<script type="text/javascript">
var seconds = <?= ($tijd+1) ?>;
var countdown = document.all? document.all["teller<?= $j?>"] : document.getElementById? document.getElementById("teller<?= $j?>") : "";
var woord = "seconden";
function display()
{
seconds=seconds-1;
if(seconds==1){ woord="seconde"; }
if(seconds==0){ woord="seconden"; }
if(seconds<0)
{
self.location.replace(self.location);
}
else
{
if (countdown)
{
countdown.innerHTML=seconds+" "+woord;
setTimeout('display()',1000);
}
}
}
display();
</script>
Your while loop goes through table rows in a DB, but your JavaScript code is not part of that loop. That means you generate a HTML table for each row, but then you create <script>...</script> which includes $tijd/$j only for the last row (assuming that your while executes before the script is added to the page.
Possible workarounds:
Add a jQuery's selector, something like $("div.teller").each(function(){...}); and in that function create a timer and/or any other JavaScript code you need associated with that div.Note that this requires your div to get a CSS class "teller".
Create all JavaScript code that is needed for each DB's table row inside the PHP's while loop, but this would probably get really messy.
Also, I advise you to take a look at JavaScript's setInterval(), since it is more appropriate than setTimeout() for what you want to do.
Another thing to consider: all your timers would have a one second tick. It seems to me that it is better to have a single timer and just keep numbers of seconds (whatever that might be) in a JavaScript array (this one is easily created in PHP's while loop).
Edit: Here is one way to do this:
$data = array();
while($info = mysql_fetch_object($dbres))
{
... /* your current code */
$data[] = "{ id: 'teller$j', seconds: $tijd }";
}
$data = "[ ".implode(", ", $data)." ]";
Now, create your JavaScript code outside of the loop:
<script type="text/javascript">
var data = <?php echo $data; ?>; // It is not advisable to use <?= ... ?>
// Get references to divs via saved ids (seconds are already saved
for (i = 0; i < data.length; i++)
data.div = document.getElementById(data.id); // No need for document.all; IE supports getElementById since version 5.5
...
</script>
Now, adapt display() to work with the elements of your data array.

Calculate time passed variable to use in $.get()

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...

Live Statistics / incrementer via Timestamp

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.

Repeat line x to y every few second in php

how i can repeat code from line x to y in php By Ajax.
for example:
mycode:
$info_2=('<div id="infobox">');
echo $chat_2;
$info_query=mysql_query("SELECT * FROM info WHERE fuid='$uid' or luid='$uid' ");
$info_num=mysql_num_rows($info_query);
for($i=0;$i<$info_num;$i++)
{
$info_fetch=mysql_fetch_array($info_query);
echo($info_fetch['username'].':'.$info_fetch['text'].'<br>');
}
$info_3=('');
echo $info_3;
now i need repeat this code every x second.
One way you can resolve this, is by executing setInterval with an Ajax call.
Somethine like :
<div id="my_container">
</div>
<script>
$(function(){loadContent()}); // first time load content
setInterval(loadContent, 2000); // every 2 seconds (2000 millis)
function loadContent()
{
$.ajax({ url:'/my_content.php',
success(result):{$("#my_container).html(result)},
error(result):{console.log(result.responseText)}})
}
</script>
However, I don't like settings intervals because it does not take into account the server time.
So this is how I would do it (pseudo code):
<div id="my_container">
<!-- include content from 'my_content.php' -->
</div>
Now for "my_content.php".
<!--- some HTML content -->....
<script>
setTimeout(function(){$.ajax({ url:'/my_content.php',
success:function(result){ $("#my_container").html(result);},
error:function(result){ console.log(result.responseText);}
}})},2000) // 2 seconds since last result
</script>
This way this piece of code is "self contained" and only requires it to be wrapped with "my_container" element.

Categories