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...
Related
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);
}
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");
}
}
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>
How do I reload this input once after 3 seconds has passed after the webpage has loaded. using javascript
<input type="text" name="steamID" id="steamID" value="<?php echo $steamid; ?>">
Try looking at this answer on SO:
Reload random div content every x seconds
If that doesn't work for you, you will have to use ajax to get new content. Look at jQuery's API here:
http://api.jquery.com/jQuery.ajax/
Or if you're not using jQuery, look at this for a tutorial on AJAX:
http://www.w3schools.com/ajax/default.asp
Otherwise, for more help, please post more of your code -- but ajax will have to be used
If you want the PHP in your code to be run again, you need to make you code a little more complicated.
You will need the following components
a php file that will lookup and print $steamid only.
a javascript function that uses AJAX to get the information from the php file, sets the value of your input
call the javascript on page load, then set an interval for 3 seconds and call it again.
But based on this...
The problem i have that the PHP var $steamid are set after the input has been created so all i need todo is reload the input so the $steamid will show.
... I think you just need to re-order your PHP code.
By reset, I am assuming you mean set the value to null.
$(window).load(function(){
setTimeout( function() {
document.getElementById("steamID").value = "";
},3000);
});
EDIT: Based on your further description, wait until steamID is set, then put this on the page:
<script type="text/javascript">
document.getElementById("steamID").value = "<?php echo $steamid; ?>";
</script>
<?php
echo "<script type='text/javascript'>";
$steamid = "testing 1,2,3";
echo " var sID = '".$steamid."';";
?>
function setupRefresh() {
setInterval("refreshVal()", 3000);
}
function refreshVal() {
var e = document.getElementById('steamID');
e.value = sID;
}
</script>
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 ?>)