Dynamic countdown for online examination system - javascript

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>

Related

Coundown Timer Inside ForEach Loop Php

I am trying to Show a Countdown Timer Inside Foreach loop for every record in PHP Codeigniter Framework, It is basically showing Datediff between current date and mysql database date value as how many days left, Below is my code.Problem is it is showing countdown timer for single record only not for every record i need
<?php foreach ($my_courses as $my_course):
$course_details = $this->crud_model->get_course_by_id($my_course['course_id'])->row_array();
<!-- countdown timer-->
<?php if ($course_details['is_onlineclass']==='Yes'): ?>
<span style="display:inline-block;font-size:12px;font-color:crimson;"><?php
$t=$course_details['live_class_schedule_time'];
//time difference in seconds for coundown timer
$date = new DateTime();
$date2 = new DateTime(date("yy-m-d h:i:s a", $t));
$diff = $date->getTimestamp() - $date2->getTimestamp() ;
echo $diff;
?></span>
<span id="<?echo $my_course['course_id']?>" class="timer" style="font-size:smaller;color:crimson;"></span>
<?php endif; ?>
<script>
var initialTime = <?echo $diff?>;
var seconds = initialTime;
function timer() {
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('<?echo $my_course['course_id']?>').innerHTML = days + "days " + hours + "hours " + minutes + "min " + remainingSeconds+ "sec left";
if (seconds == 0) {
learInterval(countdownTimer);
document.getElementById('<?echo $my_course['course_id']?>').innerHTML = "Completed";
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer()', 1000);
</script>
What is the wrong I am doing and How to show the timer for every record
Your function name and call should also be unique.
EDIT
Also you messed up a log of code. I have commented the foreach loop and put my own for loop. Modify accordingly
Try this.
<?php
$my_course['course_id'] = 0;
for($i = 0; $i <= 2; $i++):
// foreach ($my_courses as $my_course):
// $course_details = $this->crud_model->get_course_by_id($my_course['course_id'])->row_array();
// You need to comment this out when you put your code live
$course_details['is_onlineclass'] = "Yes";
$course_details['live_class_schedule_time'] = time() + rand(0, 300);
$my_course['course_id'] += 1;
// remove till here
if ($course_details['is_onlineclass']==='Yes'):
?>
<span style="display:inline-block;font-size:12px;font-color:crimson;">
<?php
$t=$course_details['live_class_schedule_time'];
//time difference in seconds for coundown timer
$date = new DateTime();
$date2 = new DateTime(date("yy-m-d h:i:s a", $t));
$diff = $date->getTimestamp() - $date2->getTimestamp() ;
?>
</span>
<span id="<?php echo $my_course['course_id']; ?>" class="timer" style="font-size:smaller;color:crimson;"></span>
<?php endif; ?>
<script>
var initialTime = <?php echo $diff; ?>
var seconds = initialTime;
function timer<?php echo $my_course['course_id'];?>() {
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('<?php echo $my_course['course_id']?>').innerHTML = days + "days " + hours + "hours " + minutes + "min " + remainingSeconds+ "sec left";
if (seconds == 0) {
learInterval(countdownTimer);
document.getElementById('<?php echo $my_course['course_id']?>').innerHTML = "Completed";
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer<?php echo $my_course["course_id"];?>()', 1000);
</script>
<?php endfor; ?>
EDIT: Here is your code
<?php
foreach ($my_courses as $my_course):
$course_details = $this->crud_model->get_course_by_id($my_course['course_id'])->row_array();
if ($course_details['is_onlineclass']==='Yes'):
?>
<span style="display:inline-block;font-size:12px;font-color:crimson;">
<?php
$t=$course_details['live_class_schedule_time'];
//time difference in seconds for coundown timer
$date = new DateTime();
$date2 = new DateTime(date("yy-m-d h:i:s a", $t));
$diff = $date->getTimestamp() - $date2->getTimestamp() ;
?>
</span>
<span id="<?php echo $my_course['course_id']; ?>" class="timer" style="font-size:smaller;color:crimson;"></span>
<?php endif; ?>
<script>
var initialTime = <?php echo $diff; ?>
var seconds = initialTime;
function timer<?php echo $my_course['course_id'];?>() {
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('<?php echo $my_course['course_id']?>').innerHTML = days + "days " + hours + "hours " + minutes + "min " + remainingSeconds+ "sec left";
if (seconds == 0) {
learInterval(countdownTimer);
document.getElementById('<?php echo $my_course['course_id']?>').innerHTML = "Completed";
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer<?php echo $my_course["course_id"];?>()', 1000);
</script>
<?php endforeach; ?>

Javascript + PHP set countodwn with form

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

javascript timer for multiple auction item not working with php

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.

24 hour Countdown timer using Javascript and PHP

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

Getting datetime from mysql into php?

I have the following code (a countdown timer using php and javascript) that I am working on. What I am trying to do is to get the datetime ($end_date) from the mysql and place it in the $date ='' inside my code.
This code will work just fine if i enter the date and time manually in the code like this: $date = 'September 17 2013 12:00:00 PM GMT';
but i need it to work some how like this:
$date = echo $dynamicList;
or like this maybe:
$date = echo $end_date;
I'm not sure what I am doing wrong!
here is my full code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>
<?php date_default_timezone_set('GMT'); ?>
<?php
session_start();
// Run a select query to get my letest 6 items
// Connect to the MySQL database
include "config/connect.php";
$dynamicList = "";
$sql = "SELECT * FROM item ORDER BY id";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query); // count the output amount
if ($productCount > 0) {
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$id = $row["id"];
$product_name = $row["product_name"];
$date_added = strftime("Y-m-d", strtotime($row["date_added"]));
$end_date = strftime("Y-m-d H:i:s", strtotime($row["end_date"]));
$price = $row["price"];
$dynamicList .= '<div>' . $end_date . '
</div>';
}
} else {
$dynamicList = "No Records";
}
?>
<?php
$date = echo $dynamicList;
$exp_date = strtotime($date);
$now = time();
if ($now < $exp_date) {
?>
<script>
// Count down milliseconds = server_end - server_now = client_end - client_now
var server_end = <?php echo $exp_date; ?> * 1000;
var server_now = <?php echo time(); ?> * 1000;
var client_now = new Date().getTime();
var end = server_end - server_now + client_now; // this is the real end time
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('countdown').innerHTML = 'EXPIRED!';
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 );
var countdown = document.getElementById('countdown');
countdown.innerHTML = '';
if (days) {
countdown.innerHTML += 'Days: ' + days + '<br />';
}
countdown.innerHTML += 'Hours: ' + hours+ '<br />';
countdown.innerHTML += 'Minutes: ' + minutes+ '<br />';
countdown.innerHTML += 'Seconds: ' + seconds+ '<br />';
}
timer = setInterval(showRemaining, 1000);
</script>
<?php
} else {
echo "Times Up";
}
?>
<div id="countdown"></div>
could someone please help me out with this?
I do not get any errors on my page. only a blank page and if I change $date = echo $dynamicList; to $date = '$dynamicList'; i get the Times Up message!
any help would be appreciated.
EDIT My new code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>
<?php date_default_timezone_set('GMT'); ?>
<?php
session_start();
// Run a select query to get my letest 6 items
// Connect to the MySQL database
include "config/connect.php";
$dynamicList = "";
$sql = "SELECT * FROM item ORDER BY id";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query); // count the output amount
if ($productCount > 0) {
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$id = $row["id"];
$product_name = $row["product_name"];
$date_added = strftime("%Y-%m-%d", strtotime($row["date_added"]));
$end_date = strftime("%Y-%m-%d %H:%M:%S", strtotime($row["end_date"]));
$price = $row["price"];
$dynamicList .= '<div>' . $end_date . '
</div>';
}
} else {
$dynamicList = "No Records";
}
?>
<?php
$date = "'".$end_date."'";
$exp_date = strtotime($date);
$now = time();
if ($now < $exp_date) {
?>
<script>
// Count down milliseconds = server_end - server_now = client_end - client_now
var server_end = <?php echo $exp_date; ?> * 1000;
var server_now = <?php echo time(); ?> * 1000;
var client_now = new Date().getTime();
var end = server_end - server_now + client_now; // this is the real end time
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('countdown').innerHTML = 'EXPIRED!';
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 );
var countdown = document.getElementById('countdown');
countdown.innerHTML = '';
if (days) {
countdown.innerHTML += 'Days: ' + days + '<br />';
}
countdown.innerHTML += 'Hours: ' + hours+ '<br />';
countdown.innerHTML += 'Minutes: ' + minutes+ '<br />';
countdown.innerHTML += 'Seconds: ' + seconds+ '<br />';
}
timer = setInterval(showRemaining, 1000);
</script>
<?php
} else {
echo "Times Up";
}
?>
<div id="countdown"></div>
Change these lines:
$date = echo $dynamicList;
With the following code:
$date = "'".$end_date."'";
And define the $end_date as a global variable.
And also add the some more parameter in the following for timezone:
$end_date = strftime("Y-m-d H:i:s A T", strtotime($row["end_date"]));
^^^ add these
You are getting the timesup message because of your if condition is not correct:
if ($now < $exp_date) {
As you are comparing the unixtimestap with the timeformat.
Use this code:
$date = "'".$end_date."'";
$exp_date = strtotime($date);
$now = strtotime(date("Y-m-d H:i:s A T"));
Then compare these time. You need to change the $now also.

Categories

Resources