Javascript timed loop with php - php

I'm trying to display the current timestamp and refresh every second, doing this with php is too slow and has to reload the page and I know javascript doesn't, I just don't know how to, any help?
<?php
$time = time() + 3600 * 15;
echo $time;
?>
<meta http-equiv="refresh" content="0.5;time.php" />
Thanks in advance.

JavaScript can call up a timestamp based on your local time. Use setInterval to loop and update the timestamp given by Date.now().
setInterval(function() {
document.getElementById("timestamp").innerHTML = Date.now();
}, 16);
See jsFiddle.

Related

how to increase a static number automatically everyday using php

I use wordpress and I have static number for a field which is taken from sql query.
<p class="counter-number">843</p>
I would like to increase that number everyday. For example when the page is loaded default number is 843 next day it should show 844 the day after it should show 845.
How can I do this? I prefer PHP but if it is possible also can use jquery.
<?php
$now = time();
$your_date = strtotime("2010-01-01"); //Starting date
$datediff = floor(($now - $your_date)/(60*60*24));
?>
<p class="counter-number"><?=$datediff?></p>
Code taken from Finding the number of days between two dates
This way it will always show the difference from the starting date to now, in days.
jQuery Answer
You will have to setup the starting date for it to increase daily. The idea is to get the date difference and add it to that counter.
HTML
<p class="counter-number">843</p>
jQuery
jQuery(function() {
// Get Starting Number
var starting_number = parseInt(jQuery('.counter-number').text());
// Create Day difference (because it increases by 1 each day)
var preset_start_date = new Date("21/03/2015");
var current_date = new Date();
var timeDiff = Math.abs(current_date.getTime() - preset_start_date.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
var final_counter = starting_number + diffDays;
jQuery('.counter-number').text(final_counter);
});
I haven't tested it. But this is an idea to get that done.
For your case here are two ways achieve the goal.
use php
//client site php_cnt.html
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>visit_cnt</title>
</head>
<script type="text/javascript"src="http://localhost/php_cnt.php">
</script>
</html>
//server site php_cnt.php
<?php
//Here is the some logic to process the visit count
$visit_cnt = 11; // assume read it from mysql
echo "document.write($visit_cnt);";
?>
use javascript/jquery
//client site php_cnt.html
$(function() {
$.get('http://localhost/php_cnt.php',{r:Math.random()},function(cnt) {
$('. counter-number').html(cnt);
});
});
//the server site code
<?php
//Here is the some logic to process the visit count
$visit_cnt = 11; // assume read it from mysql
echo visit_cnt;
?>
Hope this can help you !

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

show dynamic time with javascript

I want to show the time which I have in my php variable with the help of Javascript
I am coding an online exam module, where I want to display the total elapsed time
say for example
$time_elapsed // contains the time taken till now from the start of the exam
And if I got a div say,
<div id="time"></div>
how can I show the dynamic running time with starting from $time_elapsed after load the window for each question
Please if you guys have an answer for this..
Thanks
hi you can use the following code for the purpose
the javascript will be:
var Timer;
var TotalSeconds,TotalMins, secs;
var elapsedtime ;
function CreateTimer(TimerID, Time) {
Timer = document.getElementById(TimerID);
TotalSeconds = Time;
elapsedtime = 0
time = Time
secs = TotalSeconds%60;
TotalMins = Math.floor(TotalSeconds/60)
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
function Tick() {
if(TotalSeconds-elapsedtime>0)
{
elapsedtime += 1;
secs = (elapsedtime%60)-60;
TotalMins = Math.floor(elapsedtime/60)
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
else
alert("time up")
}
function UpdateTimer() {
Timer.innerHTML = TotalMins + ":" + secs;
}
nw create a html div where you want to show the running time.
Html:
<div id='timer' />
<script type="text/javascript">window.onload = CreateTimer("timer", 5);</script>
give parameter the time limit. it will alert after time finishes.
and to get time after refresh of the page use html5's sessionStorage
visit Html5 Storage Doc to get more details. using this you can store intermediate values temporaryly/permanently locally and then access your values
for storing values for a session
sessionStorage.getItem('label')
sessionStorage.setItem('value', 'label')
or store values permanently using
localStorage.getItem('label')
localStorage.setItem('value', 'label')
So you can store (temporarily) form data between multiple pages using html5 storage objects
This is how to display dynamic time. To use other php based starting time replace the line time0 = new Date(); by time0 =<?php echo $startTime;?>; which should be in ms since the epoch.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>elapsed time demo</title>
<script type="text/javascript">
var time0;
function initTime() {
time0 = new Date();
window.setInterval("updateTime()", 1000);
}
function updateTime() {
var timeNow = new Date();
var deltas = (Number(timeNow) - Number(time0))/1000;
var deltah = ("0"+String(Math.round(deltas / 3600))).substr(-2);
deltah = deltah.substr(-2);
deltas %= 3600;
var deltam = ("0"+String(Math.round(deltas / 60))).substr(-2);
deltas = ("0"+String(Math.round(deltas % 60))).substr(-2);
document.getElementById("timedisplay").firstChild.data=deltah+":"+deltam+":"+deltas;
}
</script>
</head>
<body onload="initTime();">
<div> elapsed time <span id="timedisplay">00:00:00</span></div>
</body>
</html>​
Your php code should return the time elapsed at the point of loading the page, however, javascript will then take over and increment that time as time passes.
You can send the parameter to your JavaScript function which is display time
function display_time(int time)
{
//your code for further integration
}
You can send the parameter to JavaScript function using following way
//call the function at the time display time
display_time(<?php echo $time_elapsed ?>)

Javascript counter on php page

I've got a java script counter on my php page. (I should probably add that I don't know java script). It display's the time the user is active on the page. My problem is if the user presses F5 or refreshes the page the counter starts from 0 again. How do I change this so that it remembers the time? Help will be greatly appreciated.
Javascript:
var pageVisisted = new Date();
setInterval(function() {
var timeOnSite = new Date() - pageVisisted;
var secondsTotal = timeOnSite / 1000;
var hours = Math.floor(secondsTotal / 3600);
var minutes = Math.floor(secondsTotal / 60) % 3600;
var seconds = Math.floor(secondsTotal) % 60;
document.getElementById('counter').innerHTML = hours + ":" + minutes + ":" + seconds;
}, 1000);
The php page
<head>
<?php
session_start();
?>
<script type="text/javascript" src="counter.js"></script>
</head>
<body>
<?php
echo "<span id='counter'></span>";
?>
</body>
You can use a cookie to do this. Since you say you don't know javascript, you might want to just review this page http://www.quirksmode.org/js/cookies.html where it tells you how to read and write cookies. Every time you evaluate the time on the site, just read/write to that cookie and it will still be there when the page reloads.

Is my code a performance killer?

I am showing the value of the timer.php through AJAX in index.php . However I am concern about the performance of this, if it is a server killer if there are 30 people online, and things like this. Do you suggest me some edits?
Thank you.
index.php
<script language='JavaScript'>
setInterval( 'SANAjax();', 1000 );
$(function() {
SANAjax = function(){
$('#dataDisplay').load('timer.php');
}
});
</script>
<div id="dataDisplay"></div>
timer.php
function time_difference($endtime){
$days= (date("j",$endtime)-1);
$hours =date("G",$endtime);
$mins =date("i",$endtime);
$secs =date("s",$endtime);
$diff="'day': ".$days.",'hour': ".$hours.",'min': ".$mins.",'sec': ".$secs;
return $diff;
}
$future_time = mktime(0, 0, 0, 9, 19, 2011);
$now_time = strtotime("+2 hours");
$end_time = $future_time - $now_time;
$difference = time_difference($end_time);
if ($future_time <= $now_time ) { echo "Date reached"; } else { echo $difference; };
?>
Depends on your server specs and number of clients, this could quickly become a server-killer.
The multiple calls to a file every second will quickly put a lot of load for nothing though, so best practice calls for using a javascript timer countdown. I particularly like this one: http://stuntsnippets.com/javascript-countdown/
And for the jQuery implementation:
<script type="text/javascript">
var myDate = new Date(); //Retrieve actual date
myDate.setTime(this.getTime() + (3600 * 2)); //Add two hours
$(document).ready(function() {
$("#time").countdown({
date: myDate.toGMTString(),
onComplete: function( event ){
$(this).html("completed");
},
leadingZero: true
});
});
</script>
<p id="time" class="time"></p>
This should be enough, no more need for PHP calls and the client does everything.
By setting a setInterval for every second, you are basically saying that for 30 clients, you will be getting roughly 30 txn per second to your php server. Its hard to say its a performance killer outside of just saying you will have to handle 30tps for this simple call. I would first quesiton why you are doing this with a server side script. You could just as easily give the html file a datetime when the page loads and do the countdown with just javascript in the browser.
I use jQuery Countdown http://keith-wood.name/countdown.html to put a timer on my pages to let the user know when they are going to be logged out of the system due to inactivity.
You can bind a function to the counter expiring event.
http://code.google.com/p/jquery-countdown/ ...Simple example
http://keith-wood.name/countdown.html ...shows off all the bells and whistles...
It can be as simple as the first one or as detailed as the second!
-=Bryan

Categories