show dynamic time with javascript - php

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 ?>)

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 !

Php date function in javascript

In this i am posting a question in which i am using a java script and PHP code and sending back the timestamp using the time function of the PHP. let have the code,
<?php
session_start();
echo time();
?>
<html>
<head>
<title>my app</title>
<script type="text/javascript" src="jquery-2.0.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(this).mousemove(function(){
var time_=new Date();
var time=<?php echo time();?>;
alert(time);
$.post('loggout.php',{input: time});
});
});
</script>
</head>
<body>
<h2>we are on the main_session</h2>
</body>
</html>
now the problem is that when i move the mouse than the mousemove event gets into action and displays the value of the var time. but every time it displays the same value. the value only changes when i reload the page. so please let me know the reason behind it and how to make this dynamic
This is because the PHP is only run once - when the page loads. So the Javascript time variable gets filled with the time returned by PHP and then never changes.
If you're happy to get the client-side time, just use this:
var time = time.getTime();
Instead of var time=<?php echo time();?>;
Otherwise, you can use AJAX to send a query that'll run some PHP, return the time, and put it into the variable.
For example, you could try something like this:
$.get('getTime.php', function(data) {
time = data;
});
And in getTime.php, just echo the time.
This is because PHP is back-end programing language and once your page loaded timestamp written to code and can't be dynamic. But you can send JS timestamp:
var time = Math.round(+new Date() / 1000);
( + will convert date Object to integer )
or
var time = Math.round(new Date().getTime() / 1000);
division by 1000 needed because JS use milliseconds.
See Date reference at MDN.
put this javascript code anywhere in your php file.
<script type="text/javascript">
var currenttime = '<?php echo date("F d, Y H:i:s"); ?>' //PHP method of getting server date
var montharray=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
var serverdate=new Date(currenttime)
function padlength(what){
var output=(what.toString().length==1)? "0"+what : what
return output
}
function displaytime(){
serverdate.setSeconds(serverdate.getSeconds()+1)
var datestring=montharray[serverdate.getMonth()]+" "+padlength(serverdate.getDate())+", "+serverdate.getFullYear()
var timestring=padlength(serverdate.getHours())+":"+padlength(serverdate.getMinutes())+":"+padlength(serverdate.getSeconds())
document.getElementById("servertime").innerHTML=timestring
}
window.onload=function(){
setInterval("displaytime()", 1000);
}
</script>
add span or div where you want to show current time. no need to reload page.
<span id="servertime"></span>

Javascript timed loop with 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.

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

Categories