javascript timer for multiple auction item not working with php - javascript

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.

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

Call Same JS function in loop to perform for all requests simultaneously

I have one function of JS which I am trying to call from inside PHP code. I am calling this JS function number of times Loop is running ( 5 for example).
Code:
<script>
//var seconds = '';
function csst(rowid){ alert(rowid);
window.setInterval(function(){
secondPassed();
function secondPassed() {
seconds = parseInt($("#ts").val());
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
$("#countdown1"+rowid).html(minutes + ":" + remainingSeconds);
if (seconds <= 0) {
clearInterval();
document.getElementById('countdown1'+rowid).innerHTML = "Buzz Buzz...";
} else {
seconds--;
$("#ts").val(seconds);
}
}
},1000);
}
</script>
<?php
$c = 1;
echo '<input type="hidden" value="50" id="ts" name="ts"/>';
echo "<table border='1'>";
while ($c <=5)
{
echo '<script>
csst('.$c.');
</script>';
echo '<tr><td>row'.$c.'</td><td><p id="countdown1'.$c.'"></td></tr>';
$c++;
}
echo "</table>";
?>
I need to have a simultaneous time decrement counter showing in each row of the table. using the same JS function.
any help, please !!
I somehow managed to solve this query.
I just to play with the pickup variable in
echo '<input type="hidden" value="50" id="ts" name="ts"/>';
using this piece of code with dynamic-id creating in the loop and likewise dynamically picking the value in the JS function helped. Any other better approach is always good to have.
updated working code:
<script>
//var seconds = '';
function csst(rowid){ //alert(rowid);
window.setInterval(function(){
secondPassed();
function secondPassed() {
seconds = parseInt($("#ts"+rowid).val());
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
$("#countdown1"+rowid).html(minutes + ":" + remainingSeconds);
if (seconds <= 0) {
clearInterval();
document.getElementById('countdown1'+rowid).innerHTML = "Buzz Buzz...";
} else {
seconds--;
$("#ts"+rowid).val(seconds);
}
}
},1000);
}
</script>
<?php
$c = 1;
echo "<table border='1'>";
while ($c <=5)
{
$val = $c+50;
echo '<input type="hidden" value="'.$val.'" id="ts'.$c.'" name="ts"/>';
echo '<script>
csst('.$c.');
</script>';
echo '<tr><td>row'.$c.'</td><td><p id="countdown1'.$c.'"></td></tr>';
$c++;
}
echo "</table>";
?>
Share any else solution as well please.

Dynamic countdown for online examination system

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>

Time countdown in an tooltip

This is my countdown script :
<script type='text/javascript'>
function cronometru(timp_ramas) {
Ore = Math.floor(timp_ramas / 3600);
minute = Math.floor((timp_ramas - Ore * 3600) / 60);
secunde = timp_ramas - minute * 60 - Ore * 3600;
if (Ore < 10){ Ore = "0"+ Ore; }
if (minute < 10){ minute = "0" + minute; }
if (secunde < 10){ secunde = "0" + secunde; }
if (timp_ramas > 0) {
timp_ramas--;
document.getElementById("timp").innerHTML = Ore + ':' + minute + ':' + secunde;
setTimeout("cronometru("+timp_ramas+")", 1000);
} else {
document.getElementById("timp").innerHTML = "Focul s-a stins !";
}
}
$timp_ramas = $citeste['timp_ramas_pentru_foc'] - time(); // this is the function that retrives the actual time from an database.
I use this "wz_tooltip.js" for the tooltip events.
<script type="text/javascript" src="wz_tooltip.js"></script>
When i try to put to show my conuntdown in the tooltip the tooltip goes black and show only the message before or after the countdown position ('Timp ramas :')
Example :
if ($citeste["timp_ramas_pentru_foc"] > 0)
{
echo "
<a onmouseover=
\"Tip('Timp ramas : <span id=timp></span> ')\"
onmouseout=\"UnTip()\">
<img src='img/skiluri/fire_yes.png'/> </a>
";
}
I found a way to make the code to work but the timer will be shown in 2 places in the same time. I want only to read it when i move the cursor on some picture / text and the tooltip apears.
Example of working code with 2 views in the same time :
$timp_ramas = $citeste['timp_ramas_pentru_foc'] - time();
?>
<script type='text/javascript'>
function cronometru(timp_ramas) {
Ore = Math.floor(timp_ramas / 3600);
minute = Math.floor((timp_ramas - Ore * 3600) / 60);
secunde = timp_ramas - minute * 60 - Ore * 3600;
if (Ore < 10){ Ore = "0"+ Ore; }
if (minute < 10){ minute = "0" + minute; }
if (secunde < 10){ secunde = "0" + secunde; }
if (timp_ramas > 0) {
timp_ramas--;
document.getElementById("timp").innerHTML = Ore + ':' + minute + ':' + secunde;
setTimeout("cronometru("+timp_ramas+")", 1000);
} else {
document.getElementById("timp").innerHTML = "Focul s-a stins !";
}
}
<script src="js/meniu_dreapta/iconmenu.js"></script>
<body>
<script type="text/javascript" src="js/tooltip/wz_tooltip.js"></script>
<span id='timp'></span> <?php echo "<script type='text/javascript'>cronometru(".$timp_ramas.")</script>"; ?>
<?php
echo '
<html>
<ul id="myiconmenu" class="iconmenu"> ';
if ($citeste["timp_ramas_pentru_foc"] > 0)
{
echo "
<a onmouseover=
\"Tip('Timp ramas : <span id=timp></span> ')\"
onmouseout=\"UnTip()\">
<img src='img/skiluri/fire_yes.png'/> </a>
";
}
Thank you.

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

Categories

Resources