Counter between 2 values with Daily Reset - php

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

Related

write in a php page with ajax

I have an a.php page containing a variable x = 10;
and a page b.php which contains var y = 10;
my question is can i add x + y and write the result in b.php? knowing that the ajax code is in a.php
<?php
if (isset($_POST['y']) && isset($_POST['x']) ) {
$y = 50;
$x=$_POST['x'];
echo $x+$y ;
}
?>
<script type="text/javascript">
$('button').on('click' , function(){
$.post('b.php' , { x:10, y:10 } , function(data){
$('div').html(data);
} );
} );
</script>
in first sight i think that you should use java script ajax on your a.php for sending data to page b.php but that is not enough so for getting you result a+b=something you need to use something called java script concurrence and those technique allow you to listen for a period of time on the existence of a so i will try to give you the solution o some steps :
Step 1: you've done your ajax sending data
step 2: you need to go check on the java script concurrence you have set interval and set timeout so use one of them but you will need to use set interval cause it will be more efficient
step 3 :use a Php condition called !empty()to check each period of time with the set Interval that a don't equal the default value if it's equal to that default value you should use clear Interval since keeping the execution of set Interval doesn't have any meaning and you will consume of the load of your page and your page will run slower
step 4: you've done with everything and you can do your operation.
i will let a short code for set Interval and you can find them on w3schools with execution example
var myVar;
function myFunction() {
myVar = setInterval(alertFunc, 3000);
}
function alertFunc() {
alert("Hello!");
}
for the clearInterval
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
function myStopFunction() {
clearInterval(myVar);
}

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

Javascript/Jquery using mysql for initial config

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;

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.

Categories