I have set_timer.php file with a form in which the admin user can set the date and time of match ending. It all works fine if I stay on the page timer.php, but when i want to include timer.php on my webpage footer it retuns Nan.
set_timer.php
<!DOCTYPE html>
<html>
<head>
<title>Natavi timer</title>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1250" />
</head>
<body>
<div id="wrapper">
<form action="timer.php" method="post">
End of the match: <input type="text" name="date" value="03/15/2015 6:30 PM"><br>
<input type="submit" value="Start">
</form>
</div>
</body>
</html>
timer.php
<?php
session_start();
$date=$_POST['date'];
?>
<!DOCTYPE html>
<html>
<head>
<title>Timer</title>
<meta charset="UTF-8" />
<script>
CountDownTimer('<?php echo $date; ?>', 'countdown');
function CountDownTimer(dt, id)
{
var end = new Date(dt);
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;
function showRemaining() {
var now = new Date();
var distance = end - now;
if (distance < 0) {
clearInterval(timer);
document.getElementById(id).innerHTML = 'Konec tekme!';
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor((distance % _day) / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
document.getElementById(id).innerHTML = ' days ';
document.getElementById(id).innerHTML += hours + ' hours ';
document.getElementById(id).innerHTML += minutes + ' minutes ';
document.getElementById(id).innerHTML += seconds + ' seconds';
}
timer = setInterval(showRemaining, 1000);
}
</script>
</head>
<body>
<div id="countdown"></div>
</body>
</html>
And then i just include my timer.php in the webpage footer.
<div id="footer"><?php include 'timer.php'; ?></div>
Looking at the code again, I think this is your error:
session_start();
$date=$_POST['date'];
Should be
session_start();
$date=$_SESSION['date'];
To make proper use of the session variables.
The $date comes from a $_POST not from session, so, when you include timer.php with you don't actually send anything in post and naturally you have nothing in $date variable. You need to set the data in the session after submitting the form, then read it from there.
Also as tips... your code have multiple problems:
Php js and html on same file -> this is usually a bad idea
Session start after output sent (added after reading comments - Bulk, did not notice it at first glance)
Multiple variables meaning the same think -> waste of memory
Footer after < /html>
Others (lack of comment, etc.)
Related
I am developing an online examination system in PHP and MySQL. Each exam has got its own period which is stored in the database, and the system shows one question at a time. When the submit button is pressed, it submits the question then displays the next one.
I tried to use the below code for the timer, and it appears for the student but once the first question is submitted and the second one appears the timer starts from the beginning again. For example, if the time was twenty minutes, it starts again from twenty minutes when the second question appears.
This is the code that I used:
<html>
<head></head>
<body>
<?php
$db = mysql_connect("localhost", "root", "");
mysql_select_db("exam", $db);
$result = mysql_query("SELECT * FROM test");
while($row = mysql_fetch_array($result)) {
$min = $row['minutes'];
}
?>
<div id="quiz-time-left"></div>
<script type="text/javascript">
var min = '<?php echo $min;?>';
var total_seconds = 60 * min;
var c_minutes = parseInt(total_seconds / 60);
var c_seconds = parseInt(total_seconds % 60);
function CheckTime() {
document.getElementById("quiz-time-left").innerHTML = 'Time Left: ' + c_minutes + 'minutes' + c_seconds + 'seconds';
if (total_seconds <= 0) {
setTimeout('document.quiz.submit()', 1);
} else {
total_seconds = total_seconds - 1;
c_minutes = parseInt(total_seconds / 60);
c_seconds = parseInt(total_seconds % 60);
setTimeout("CheckTime()", 1000);
}
}
setTimeout("CheckTime()", 1000);
</script>
<form name=quiz method="post" action="process.php"></form>
I'm making a calculator where a user can enter in a date, and it will display the time elapsed since. I've got it so that after the user clicks the submit button I've coded in, the page refreshes and displays a query string as follows:
file:///H:/dateselection/public_html/Document8.html?
Note the question mark at the end.
My question is, how do I take this and pass it into a value so that I can display it on my page? Here is my code:
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<Title>Elapsed Time Calculator</Title>
<body>
<!-- Navigation -->
<nav>
<ul class="w3-navbar w3-black">
<li>Home</li> <!--Link to Home Page-->
<li>NHL Teams</li><!--Link to Page of NHL Teams-->
<li>AHL Teams</li><!--Link to Page of AHL Teams-->
<li>WHL Teams</li><!--Link to Page of WHL Teams-->
<li>G.A.A. Calculator</li><!--Link to Page of WHL Teams-->
<li>Fan Survey</li><!--Link to Fan Survey Page-->
<li>Web Safety</li><!--Link to Page about Web Safety-->
<li>Elapsed Time</li><!--Link to Page That Calculates Elapsed Time Between Two Dates-->
</ul>
</nav>
<header>
<h1 style="text-align:center;">Elapsed Time Calculator</h1>
</header>
<article>
<form id="frmdate" onsubmit="myfunction()">
<fieldset>
<label for="dateSelected">
Select a date
</label>
<input type="date" id="dateSelected" />
</fieldset>
<fieldset class="button">
<button type="submit" id="determineDay">Calculate</button>
</fieldset>
</form>
</article>
<div id="output"></div>
<script src="tools.js"></script>
</body>
</html>
Here is my script file:
function myfunction()
{
var enteredDate = document.getElementById('dateSelected').valueAsDate;
var a= new Date();
var elapsed_time = a- enteredDate;
var result=elapsed_time.toString('days-hours-minutes-seconds');
//var result = "Day: " + elapsed_time.getDate() + "<br/>" +
// "Month: " + elapsed_time.getMonth() + "<br/>" +
// "Year: " + elapsed_time.getFullYear();
//document.getElementById('output').innerHTML = "Result is:<br/>" + result;
}
function secondsToString(result)
{
var numyears = Math.floor(result / 31536000);
var numdays = Math.floor(( result % 31536000) / 86400);
var numhours = Math.floor(((result % 31536000) % 86400) / 3600);
var numminutes = Math.floor((((result % 31536000) % 86400) % 3600) / 60);
var numseconds = (((result % 31536000) % 86400) % 3600) % 60;
return numyears + " years " + numdays + " days " + numhours + " hours " + numminutes + " minutes " + numseconds + " seconds";
}
In fact because you are using js and isn't really submitting anything, you can just disable form onsubmit and work with the "submit button" onclick event.
function myfunction() {
var enteredDate = document.getElementById('dateSelected').valueAsDate;
var a = new Date();
var elapsed_time = a - enteredDate;
var result = new Date(elapsed_time);
var result = "Day: " + result.getDate() + "<br/>" +
"Month: " + result.getMonth() + "<br/>" +
"Year: " + result.getFullYear();
document.getElementById('output').innerHTML = "Result is:<br/>" + result;
}
function secondsToString(result) {
var numyears = Math.floor(result / 31536000);
var numdays = Math.floor(( result % 31536000) / 86400);
var numhours = Math.floor(((result % 31536000) % 86400) / 3600);
var numminutes = Math.floor((((result % 31536000) % 86400) % 3600) / 60);
var numseconds = (((result % 31536000) % 86400) % 3600) % 60;
return numyears + " years " + numdays + " days " + numhours + " hours " + numminutes + " minutes " + numseconds + " seconds";
}
var calculateButton = document.getElementById('determineDay');
calculateButton.onclick = myfunction;
<form id="frmdate" onsubmit="return false;">
<fieldset>
<label for="dateSelected">
Select a date
</label>
<input type="date" id="dateSelected" />
</fieldset>
<fieldset class="button">
<button id="determineDay">Calculate</button>
</fieldset>
</form>
<div id="output"></div>
I get the GMT time in PHP and I would like to make it count, like the clocks.
<?php $time = gmdate('H:i:s'); ?>
<script>var time = <?php echo($time) ?>;
setInterval(function() {
time += 1;
$("#timediv").text("Current time (GMT): " + time);
//somehow convert it to 11:44:31 AM ??
}, 1000);
</script>
Can seomeon help me?
First of all, relying on setTimeout/setInterval accuracy for displaying time is not a good idea. There are multiple reasons for them not being that accurate, like CPU slowdowns. That's why you should rather use Date object, which uses actual clock.
This is what I do when I want to use my server's time on the client side:
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<!-- dateFormat plugin for nice and easy time formatting -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-dateFormat/1.0/jquery.dateFormat.min.js"></script>
<script>
var clientTime = (new Date()).getTime(),
serverTime = <?php echo time() ?> * 1000,
difference = clientTime - serverTime;
setInterval(function () {
var now = new Date();
now.setTime(now.getTime() - difference);
$("#timediv").text("Current time (GMT): " + $.format.date(now, "hh:mm:ss a"));
}, 1000);
</script>
The key concept behind it is to calculate the difference between server time and client time. Then, you normalize your client side (created each time with new Date()) with the difference. We are still using setInterval, but even if it's delayed or accelerated for some reason, the time displayed is still correct.
I would not follow motanelu's answer but change it to this:
<script>var time = Date.parse('<?php echo($time) ?>');
setInterval(function() {
time.setSeconds(time.getSeconds() + 1);
$("#timediv").text("Current time (GMT): " + time);
//somehow convert it to 11:44:31 AM ??
}, 1000);
</script>
This creates a Date object which can you can format with for example time.toLocaleTimeString();
Replace
<?php $time = gmdate('H:i:s'); ?>
with
<?php $time = gmdate('h:i:s A'); ?>
Thank you guys, I made it:
PHP:
$time = gmdate('H:i:s');
$time = preg_replace("/^([\d]{1,2})\:([\d]{2})$/", "00:$1:$2", $time);
sscanf($time, "%d:%d:%d", $hours, $minutes, $seconds);
$timeInSeconds = $hours * 3600 + $minutes * 60 + $seconds;
Javascript:
<script>
function fromSeconds(sec){
var d=new Date(0,0,0);
d.setSeconds(+sec);
return (d.getHours() ? d.getHours()+":" : "")+d.getMinutes()+":"+d.getSeconds();
}
var time = <?php echo($timeInSeconds) ?>;
var newTime = 0;
setInterval(function() {
time += 1;
var newTime = fromSeconds(time);
$("#timediv").text("The current GMT time is: " + newTime);
}, 1000);');
?>
</script>
I'm trying to implement a countdown timer for the online auction project, But it's only working for one item displayed. Here is the code:
<?php
$result=mysql_query("select * from `date`")or die(mysql_error());
while($row=mysql_fetch_array($result))
{
$then = $row['date'];
$now = time();
$thenTimestamp = strtotime($then) + strtotime($now);
$difference = $thenTimestamp - $now;
echo '<script type="text/javascript">
var seconds ='.$difference.';
function secondPassed() {
var hours=Math.round(seconds / 3600);
var minutes = Math.round(((seconds - 30)/60)%60);
var remainingSeconds = seconds % 60;
document.getElementById("countdown").innerHTML = hours+ ":"+ minutes + ":" + remainingSeconds;
if (seconds == 0) {
// clearInterval(countdownTimer);
document.getElementById("countdown").innerHTML = "Buzz Buzz";
} else {
seconds--;
}
}
setInterval("secondPassed()", 1000);
</script>
<body>
<span id="countdown"></span>
</body>';
}
?>
I have to submit my project on online auction by tomorrow. so, i need the solution. please help me out.
Thanks in advance.
I need a 24 hour countdown timer like the image in the link. I need to implement the timer to my wordpress site. The timer should reset every night at midnight EST.
This is my current JS Code but it restarts each time i refresh the page. Can I somehow integrate it with EST?
<script type = "text/javascript">
var timeInSecs;
var ticker;
function startTimer(secs) {
timeInSecs = parseInt(secs);
ticker = setInterval("tick()", 1000);
}
function tick( ) {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
}
else {
clearInterval(ticker);
startTimer(172800); // start again
}
var hours= Math.floor(secs/3600);
secs %= 3600;
var mins = Math.floor(secs/60);
secs %= 60;
var pretty = ( (hours < 10 ) ? "0" : "" ) + hours + ":" + ( (mins < 10) ? "0" : "" ) + mins + ":" + ( (secs < 10) ? "0" : "" ) + secs;
document.getElementById("countdown").innerHTML = pretty;
}
startTimer(86400); // 24 hours in seconds
</script>
<span id="countdown" style="font-weight: bold;"></span>
I'll take another look at this when I am home, your problem however is that every time your page loads you are calling the startTimer() method, what you need to do is get the current system time (in EST format) and convert that to seconds
That way when your page refreshes you will have the current time and not your current defined constant - I hope this is a basis for you to find a solution.
I got the answer. as Alex said, I need to get current system time(EST). I came up with index.html and server_time.php files.Here are codes for both files
INDEX.HTML
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Countdown</title>
<script src="http://code.jquery.com/jquery-2.1.0.js"></script>
<script>
var root_path = "http://localhost/countdown/";
function init(){
$.ajax({
type: "POST",
url: root_path + "server_time.php",
beforeSend: function(aj_msg) {
//$("#countdown").html('');
},
success: function(aj_msg){
$("#countdown").html('');
phpMsg = JSON.parse(aj_msg);
var est = "<span>" + Math.abs(phpMsg['ServerTime'][0].hour) + " :</span> ";
est += Math.abs(phpMsg['ServerTime'][0].minute) + " : " ;
est += Math.abs(phpMsg['ServerTime'][0].second);
$("#countdown").html(est);
}
})
}
setInterval(init, 1000)
</script>
</head>
<body>
<div id="countdown"></div>
</body>
</html>
And server_time.php
<?php
date_default_timezone_set('US/Eastern');
$currenttime = date('G:i:s:u');
list($hrs,$mins,$secs,$msecs) = split(':',$currenttime);
$output = '{"ServerTime": [';
$hrs -= 24;
$mins -= 60;
$secs -= 60;
$output .= '{ "hour":"' . $hrs . '" , "minute":"' . $mins . '", "second":"' . $secs . '"}';
$output .=']}';
echo $output;
?>