Multiple Countdown using PHP and Javascript - javascript

I am currently stuck on a problem and not sure how to solve it. I am new to php and javascript coding so do please correct me if there is an easier way to do this.
My problem is that I am trying to get a countdown timer working for multiple data in mysql database. I have already made a successful countdown time function that only works with one data using the if statement in php, but when I try to do it with multiple data using the while statement in php it doesn't work.here is my php code
//TODAY'S DATE
$today = time();
//FETCHES DATE AND TIME FOR THE EVENT FROM DATABASE
$sql = "SELECT * FROM post";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$title = $row['title'];
$cname = $row['cname'];
$team = $row['team'];
$description = $row['description'];
$endtime = $row['endtime'];
echo "<tr>";
echo "<td width='16%'><strong>Title:</strong></td>";
echo "<td width='16%'>$title</td>";
echo "</tr><tr>";
echo "<td width='16%'><strong>Client name:</strong></td>";
echo "<td width='16%'>$cname</td>";
echo "</tr><tr>";
echo "<td width='16%'><strong>Team:</strong></td>";
echo "<td width='16%'>$team</td>";
echo "</tr><tr>";
echo "<td width='16%'><strong>Description:</strong></td>";
echo "<td width='16%'>$description</td>";
echo "</tr><tr>";
echo "<td width='16%'><strong>End time:</strong></td>";
echo "<td width='16%'>$endtime</td>";
echo "</tr><tr>";
echo"</BR>";
echo"</BR>";
}
$conn->close();
below is my javascript that suppose to run the count down
<script language="JavaScript">
var today = new Date();
var DD = today.getDate();
var MM = today.getMonth()+1; //January is 0!
var YYYY = today.getFullYear();
//let get the Difference in Sec btw the two dates
var _DateFromDBProgEndDate = '<?php echo $endtime; ?>';
var ProgEndTime = new Date(_DateFromDBProgEndDate);
var TodayTime = new Date();
var differenceTravel = ProgEndTime.getTime()- TodayTime.getTime() ;
var seconds = Math.floor((differenceTravel) / (1000));
////////////////////////////////
var SecDiffFromToday = seconds;
var seconds = SecDiffFromToday;
function pad(n) {
// utility function to pad a number to 2 digits:
return ('0' + n).substr(-2);
}
function timer() {
var todaySeconds = Math.floor(new Date().getTime() / 1000);
// collect the html first in an array
var html = [];
// keep track whether there are still counters not yet zero:
var allDone = true;
// go through the list of dates:
endDatesInSeconds.forEach(function (endDateSeconds) {
var totalSeconds = endDateSeconds - todaySeconds;
var days = Math.floor(totalSeconds/24/60/60);
var seconds = Math.floor(totalSeconds - days*86400);
var hours = Math.floor(seconds/3600);
seconds = Math.floor(seconds - hours*3600);
var minutes = Math.floor(seconds/60);
seconds = seconds % 60;
// add a part of html
html.push(
totalSeconds <= 0
? 'project time Completed'
: days + ":" + pad(hours) + ":" + pad(minutes) + ":" + pad(seconds));
// when at least one counter is not complete, we are not done:
allDone = allDone && totalSeconds <= 0;
});
// now put the html in the document:
document.getElementById('countdown').innerHTML = html.join('<br/>');
if (allDone) {
clearInterval(countdownTimer);
}
}
var countdownTimer = setInterval('timer()', 1000);
</script>
the javascript run the countdown by getting it value from the php (var _DateFromDBProgEndDate = '<?php echo $endtime; ?>';)

Related

Timer in Every Row of Table

I would like to add a running time/ stopwatch for every row showing the time spent in each process. The timer just shows at the first row and nothing on the rest.
The date to be used would come from a database.
Here's a snippet of my code for reference:
<?php
echo "<h2>On-Going Repairs</h2>";
$query = "SELECT tca_ro, tca_csplate, tca_name, tca_start, tca_process FROM tcs.tca_bp_process WHERE date(tca_start) = curdate() AND tca_status = 'Started'";
if($query_result = mysqli_query($link,$query)){
if(mysqli_num_rows($query_result) > 0)
{
echo "<div class='card-body'>";
echo "<div class='table-responsive'>";
echo "<table class='table table-bordered' id='dataTable' width='100%' cellspacing='0'>";
echo "<thead>";
echo "<tr>";
echo "<th>RO NUMBER</th>";
echo "<th>CS NUMBER</th>";
echo "<th>TECHNICIAN</th>";
echo "<th>START</th>";
echo "<th>PROCESS</th>";
echo "<th>DURATION</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
while ($row = mysqli_fetch_array($query_result))
{
echo "<tr>";
echo "<td>".$row['tca_ro']."</td>";
echo "<td>".$row['tca_csplate']."</td>";
echo "<td>".$row['tca_name']."</td>";
echo "<td><input type='text' id='date' value='".$row['tca_start']."'</td>";
echo "<td>".$row['tca_process']."</td>";
echo"<td><div id='data'></div></td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
echo "</div>";
echo "</div>";
}
}
?
<script type="text/javascript">
function func(){
var dateValue = document.getElementById("date").value;
var date = Math.abs(new Date(dateValue).getTime() / 1000).toFixed(0);
var currentDate = Math.abs((new Date().getTime() / 1000).toFixed(0));
var diff = currentDate - date;
var hours = Math.floor(diff/3600) % 24;
var minutes = Math.floor(diff/60) % 60;
var seconds = diff % 60;
var time_str = hours + " : " + minutes +" : "+ seconds
document.getElementById("data").innerHTML =hours+":"+minutes+":"+seconds;
}
func();
setInterval(func, 1000);
</script>
Hope you can help me out. Thank you in advance
You have no need for Timer as they are in the Java programming language. All you need to do is display the values from a database.
Assuming you have start and end times in tca_start and tca_end, and duration in tca_duration just add lines as
echo "<td>".$row['tca_start']."</td>";
echo "<td>".$row['tca_end']."</td>";
echo "<td>".$row['tca_duration']."</td>";
If that is not what you are looking for, maybe enhance you question.

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

echo time doesn't work

I want to echo the time of the server, or the time in Europe/London or Europe/Lisbon.
This is my code but for some reason it's displaying the time on the system or something. I mean, in my PC I see the correct time but in a tablet which is an hour late it shows the time of the tablet o.O
here's the code:
<?php
$date = new DateTime("now", new DateTimeZone('Europe/Lisbon') );
$today = getdate($date); ?>
<script>
var d = new Date(Date.UTC(<?php /*echo $today['year'].",".$today['mon'].",".$today['mday'].",".$today['hours'].",".$today['minutes'].",".$today['seconds'];*/ echo $date->format('Y,m,d,H,i,s'); ?>));
setInterval(function() {
d.setSeconds(d.getSeconds() + 1);
$('#timer').text((d.getHours() +':' + d.getMinutes() + ':' + d.getSeconds() ));
}, 1000);
</script>
<p><div id="timer"></div></p>
You can do it using JavaScript
Example:
setInterval(function() {
var date = new Date();
var H = date.getHours();
var M = date.getMinutes();
var S = date.getSeconds();
$('#timer').text(H+':'+M+':'+S);
},1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="timer"></div>
<?php
$date = new DateTime("now", new DateTimeZone('Europe/Lisbon');
$today = $date->format('Y-m-d H:i:s');
?>
<div id="timer"></div>
<script>
var d = new Date('<?php echo $today ?>');
setInterval(function() {
d.setSeconds(d.getSeconds() + 1);
document.getElementById('timer').innerHTML=(d.getHours() +':' + d.getMinutes() + ':' + d.getSeconds() );
}, 1000);
</script>

jQuery countdown - apply to new elements loaded via AJAX / PHP

I have a container div which loops through items in a PHP array to generate repeating element divs all with a unique ID.
I am using a countdown plugin (http://keith-wood.name/countdown.html) to apply to a date on each element and it worked out in PHP.
This all works fine until I load more elements into the page using AJAX /PHP. The countdown isn't applied to the new items and I am struggling to figure out how I would do this.
echo "<div class=\"item\" id=\"item_$id\">
<h4 class=\"name\">$Name</h4>
<p>$Cat</p>";
if ($expires != '') {
$year = date('Y', strtotime($discount['expires']));
$month = date('n', strtotime($discount['expires']));
$day = date('d', strtotime($discount['expires']));
$hour = date('H', strtotime($discount['expires']));
$minute = date('i', strtotime($discount['expires']));
$secs = date('s', strtotime($discount['expires']));
$countdown_html = '<div class="defaultCountdown" id="countdown_' . $id . '" data-year="'. $year .'" data-month="'. $month .'" data-day="'. $day .'" data-hour="'. $hour .'" data-minute="'. $minute .'" data-secs="'. $secs .'"></div>';
echo "<script type=\"text/javascript\">
$(window).load(function(){
var year = $('#countdown_$id').attr('data-year');
var month = $('#countdown_$id').attr('data-month');
var day = $('#countdown_$id').attr('data-day');
var hour = $('#countdown_$id').attr('data-hour');
var minute = $('#countdown_$id').attr('data-minute');
var secs = $('#countdown_$id').attr('data-secs');
$('#countdown_$id').countdown({until: new Date(year, month - 1, day, hour, minute, secs)});
});
</script>";
}
echo "</div>\n";
}
function loadMoreItems(getQuery, page) {
//load items
$.get(getQuery, null, function(data) {
var container = $(data).find('#container');
if (container) {
var newItemsHTML = "";
newItemsHTML = $(container).html();
var $newItems = $(newItemsHTML);
$container.isotope('insert', $newItems, true);
//add jquery effects to new elements
$newItems.find('.hcaption').hcaptions({effect: "fade"});
$newItems.find(".live-tile").liveTile({pauseOnHover: true});
$('.defaultCountdown').each( function() {
var year = $(this).attr('data-year');
var month = $(this).attr('data-month');
var day = $(this).attr('data-day');
var hour = $(this).attr('data-hour');
var minute = $(this).attr('data-minute');
var secs = $(this).attr('data-secs');
$('#' + this.id).countdown({until: new Date(year, month - 1, day, hour, minute, secs)});
});
}
}, 'html');
}
After your ajax function returns, just call the jquery to initialise the countdowns again.
Instead of using php to echo the values into the jQuery call - add them to the div itself, e.g
<div class="defaultCountdown" data-year="2013" data-month="11">
Then to initialise it would be:
$('div.defaultCountdown').each( function() )
{
year = $(this).attr('year');
...
$(this).countdown({until: new Date(year, month - 1, day, hour, minute, secs)});
});
Add some way of checking if an element has already been processed. You could create the elements initially with class="unprocessed"
<div class="defaultCountdown unprocessed">
The countdown initialise function would then be:
$('div.defaultCountdown.unprocessed').each(function(){...})
After the countdown has been initialised remove the 'unprocessed' class name
$(".element").each(function() {
var item_id = "#" + this.id;
if(this.id != 'discount_0'){
container.find(discount_id).remove();
}
$(element_id).countdown({until: new Date($year, $month - 1, $day, $hour, $minute, $secs)});
});
when you are applying countdown you are calling on $(element_id), it should be
$(item_id)
and you are using $year, $month - 1, $day, $hour, $minute, $secs all these are php variables,you cannot use them as jquery variables

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