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.
Related
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 !
So I am trying to do what I think is the impossible. I want to destroy all session cookies on browser or tab close, so I came up with a solution, I am just having small issues with JavaScript formatting. This does have to be time based, as when the next page reloads, it will put the timer for expiration for a year, so that other pages on my site don't delete the cookies as well. So until they navigate away from the site or close the tab, the cookie wont expire.
So The JavaScript starts like this:
var today = new Date();
today.setSeconds(today.getSeconds() + 5);
alert(today);
window.onunload = function(){
document.cookie = 'PHPSESSID=; expires=' + today;
};
So When I run this, it does not recognize the today variable, or I am not formatting today correctly.
All help is appreciated!
The today variable is out of scope. You need to create it in the unload, or pass it in the function().
window.onunload = function(today){
document.cookie = 'PHPSESSID=; expires=' + today.getTime();
};
OR
window.onunload = function(){
var today = new Date();
today.setSeconds(today.getSeconds() + 5);
document.cookie = 'PHPSESSID=; expires=' + today.getTime();
};
So I decided to destroy the session cookies with a small script.
This is what I came up with.
window.onunload = function(){
var today = new Date();
today.setSeconds(today.getSeconds() + 2);
var today1= today.toUTCString()
document.cookie =
'PHPSESSID=<?php echo $sesid; ?>; expires='+ today1 +'; path=/'
alert(document.cookie);
};
So This will set the destroy to 2 seconds, but if you navigate to any other page on my site, it will run this first.
var today2 = new Date();
today2.setSeconds(today2.getSeconds() + 10000);
var today3= today2.toUTCString()
document.cookie =
'PHPSESSID=<?php echo $sesid; ?>; expires='+ today3 +'; path=/';
This allows the session to be destroyed anytime you navigate away from the page.
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.
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 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 ?>)