Php date function in javascript - php

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>

Related

Javascript Date not giving tupdated value

here i was making a sample program in php.In which i included the java script and used the date but i am getting the same date every time.let have a look on the code.
<?php
?>
<html>
<head>
<title>my app</title>
<script type="text/javascript" src="jquery-2.0.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var time1=new Date();
var time_stack=new Array();
var time;
$(this).mousemove(function(){
time=time1.getSeconds();
alert(time1);
});
});
</script>
</head>
<body>
<h2>we are on the main_session</h2>
</body>
</html>
now the problem is that when i move the mouse than i get an alert box popping out and the date which is being displayed is same all time.Please let me know the problem
Try this
$(document).ready(function(){
$(this).mousemove(function(){
var time1=new Date();
time=time1.getSeconds();
alert(time);
});
});
Hope it will help
Hi, You should assign value for time1 variable in the mousemove() function. Use like this:
$(this).mousemove(function(){
var time1 = new Date();
var time_stack = new Array();
var time;
time = time1.getSeconds();
alert(time1);
});
This is because time1 is evaluated only once when the page loads, on every mouse event you just get the seconds from when it was initialized
The variable time1 never changes, the Date object is the same, so you always get the same time ?
You have to either update the Date on each mousemove, or just get a new Date object :
<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 time1 = new Date();
console.log( time1.getSeconds() );
});
});
</script>
</head>
<body>
<h2>we are on the main_session</h2>
</body>
</html>
FIDDLE
The Date object your instancing isn't a stop watch that will get the current time when you call a method on it. You need to instances a new Date object in your event handler.
alert(new Date().getSeconds());
There is a misprint:
alert(time), not time1 and try this:
$(this).mousemove(function(){
var time1=new Date();
time=time1.getSeconds();
alert(time);
});

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

PHP and jQuery function—only works once?

I have the following function. When I click the first time, it returns a random number, but all subsequent clicks always return the same number. How come it doesn't refresh?
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#btn-get-random-image').click(function () {
$('#my-img').attr('src', '<?php echo $pics[array_rand($pics, 1)]; ?>');
});
});
</script>
It's because you're using PHP to generate the random number, and it can't possibly be refreshed across calls to the JS function -- it's embedded in the HTML by that point.
May be you can also use live like instead of click
$(document).ready(function(){
$('#btn-get-random-image').live("click", function () {
// your works here
}
});
also check out jquery live
As others have said, you are using PHP, which is executed once on the server and sent as raw output, so the image will not change. Try this!
Edit: modified code to make it suck less.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
var myPics = <?php echo json_encode($pics); ?>;
$(document).ready(function() {
$('#btn-get-random-image').click(function () {
var index;
do {
index = Math.floor(Math.random() * myPics.length);
} while ( typeof myPics[index] == 'undefined' );
$('#my-img')
.attr('src', myPics[index]);
});
});
</script>
This uses PHP's JSON encoder to dump your array to the javascript, then your function randomly selects an image from that array to display. The do/while loop might not be necessary, my testing shows a pretty good near-uniform distribution over thousands of iterations, but there it is nonetheless.
Your PHP is creating JS code, which gets sent to the browser once when the page is rendered. Each call to the JS function runs the function as it existed when the page was rendered.

how can i iterate through the urls in an array, displaying each in an iframe?

The purpose of this code is to loop through the urls and insert the latest one into the iframe. Below, I am using jquery's countdown plugin.
<?php
$count=0;
$urls[]="http://www.techcrunch.com";
$urls[]="http://www.livingsocial.com";
$urls[]="http://www.guardian.co.uk";
$urls[]="http://www.google.com";
$urls[]="http://www.rightmove.com";
$urls[]="http://www.godaddy.co.uk";
foreach ($urls as $count){
?>
<script type="text/javascript">
$(function start() {
var changetimer = new Date();
changetimer.setSeconds(changetimer.getSeconds() + 10.5);
$('#defaultCountdown').countdown({until: changetimer, onExpiry: liftOff});
$('#year').text(changetimer.getFullYear());
});
function liftOff() {
document.getElementById("mainview").src = '<?php echo($count); ?>';
}
</script>
<?php } ?>
</head>
the below is in the body tag
<iframe id="mainview" width="800" height="400" src="http://www.holidays.com">
</iframe>
The problem here is this code skips through the list of urls so quickly you only see the first one, and the last url. The urls inbetween are so far invisible and the countdown timer only appears once. I am using the jquery countdown plugin.
How do I make this slow down and show each iteration of the count down individually before moving to the next? thank you very much.
The problem is that you are setting all of your timers to go off at exactly the same time. You need to set them for different times. Instead of adding 10.5 seconds for each one, maybe add "10.5*the array index" so that each one waits a little longer than the previous.
Do it like this:
<?php
$count=0;
$urls[]="http://www.techcrunch.com";
$urls[]="http://www.livingsocial.com";
$urls[]="http://www.guardian.co.uk";
$urls[]="http://www.google.com";
$urls[]="http://www.rightmove.com";
$urls[]="http://www.godaddy.co.uk";
?>
<script type="text/javascript">
$(function start() {
var changetimer = new Date();
changetimer.setSeconds(changetimer.getSeconds() + 10.5);
var urls = <?php echo json_encode($urls); ?>;
$.each(urls, function(i, url){
setTimeout(function(){
liftOff(url);
} ,5000*i); //Change every 5 seconds
});
$('#year').text(changetimer.getFullYear());
});
function liftOff(url) {
document.getElementById("mainview").src = url;
}
</script>

Categories