Javascript/PHP countdown timer stops at a certain time? - javascript

I have this code for a countdown timer. its basically a combination of PHP/Javascript countdown timer which will gets the $end_date from a Mysql table/field.
The problem is that it will stop automatically (which is unwanted) at a certain time.
For example: I set the $end_date to September 19 2013 11:30:00 AM GMT in mysql database.
the countdown starts and works fine and starts counting down as it should. However, when the countdown timer reaches September 19 2013 13:00:00 PM GMT it will stop and it will show the Times Up message! Basically it will stop working or counting down once the $end_date has been changed to 13:00:00 PM.
I cannot see anything in my code that will cause this issue. apart from this line:
if ($now < $exp_date ) {
?>
but again, this line only tells the script when to start counting and as far i can see it shouldn't stop the countdown timer to stop as long as the timer has not reached the $end_date. or am I missing something?
here is my 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 = date("Y-m-d", strtotime($row["date_added"]));
$end_date = date("F d Y H:i:s A T", 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>
any help would be greatly appreciated.

13:00:00 PM is not a valid time. AM and PM are used to indicate which side of the 12-hour cycle the time is. You cannot logically say you're on the 13th hour of the 12 hour side of the clock.
EDIT: For clarity: 13:00 == 1 PM, 13:00 PM == nothing.

Related

Countdown timer goes into negative numbers instead of replacing html

I made this countdown timer to show a video after it reaches the end. However it just goes into negative numbers. Seems to be related to the part of the code to hide the content after expiry date. Here is a JS fiddle
<div id="countdown"></div>
<div id="playsession"></div>
<script>
var releaseDate = new Date('05/29/2021 9:00 UTC+1');
var expiryDate = new Date('10/11/2021 01:00AM UTC+1');
var cdNotice = 'This session will appear automatically when the countdown finishes';
var trDay = ' Days';
var trHours = ' Hours';
var trMin = ' Minutes';
var trSec = ' Seconds';
var media = "<div class=\"wistia_responsive_padding\" style=\"padding:56.25% 0 0 0;position:relative;\"><div class=\"wistia_responsive_wrapper\" style=\"height:100%;left:0;position:absolute;top:0;width:100%;\"><iframe src=\"https:\/\/fast.wistia.net\/embed\/iframe\/eiwj630vxa?videoFoam=true\" title=\"June 19 & 20 ~ Refresh & Revive ~ Gen Rabten ~ 1 Video\" allow=\"autoplay; fullscreen\" allowtransparency=\"true\" frameborder=\"0\" scrolling=\"no\" class=\"wistia_embed\" name=\"wistia_embed\" allowfullscreen msallowfullscreen width=\"100%\" height=\"100%\"><\/iframe><\/div><\/div>\r\n<script src=\"https:\/\/fast.wistia.net\/assets\/external\/E-v1.js\" async><\/script>";
</script>
Above I set the start time and expiry time.
If the person loads the page before the countdown ends it should show the countdown. If the person loads after the countdown it will show the video.
If the person loads the page after the expiry time it should show the expired message.
Timer
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 = releaseDate - now;
var gone = expiryDate - now;
if (distance < 0 && gone > 0) {
clearInterval(timer);
document.getElementById('countdown').innerHTML = "";
document.getElementById('playsession').innerHTML = media;
return;
}
if (gone < 0) {
clearInterval(timer);
document.getElementById('playsession').innerHTML = '<p>This video has now expired</p>';
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('countdown').innerHTML = '<p>' + cdNotice + '</p>';
document.getElementById('countdown').innerHTML += '<p>';
if (days > 0) {
document.getElementById('countdown').innerHTML += '<b>' + days + trDay + '</b> ';
}
if (hours > 0) {
document.getElementById('countdown').innerHTML += '<b>' + hours + trHours + '</b> ';
}
if (minutes > 0) {
document.getElementById('countdown').innerHTML += '<b>' + minutes + trMin + '</b> ';
}
document.getElementById('countdown').innerHTML += '<b>' + seconds + trSec +'</b>';
document.getElementById('countdown').innerHTML += '</p>';
}
timer = setInterval(showRemaining, 1000);
Your expire date is incorrect, add space before AM, then it will work, otherwise your condition is not met, because gone = NaN.
With this it works correctly:
var expiryDate = new Date('10/11/2021 01:00 AM UTC+1')

How to auto update database mysql using javascript in html

I want to auto update my database when the countdowntimer is == 0 or < 0 without reloading the page. Only a certain block will be reload or reload the script/code. How can i auto update my database in mysql when the distance is < 0? I try the reload(); and .load(location.href("#")); But they reload the page.
I use PHP as my backend
In JAVASCRIPT
<script type="text/javascript">
function createCountDown(elementId, date) {
var countDownDate = new Date(date).getTime();
var x = setInterval(function() {
var now = new Date().getTime();
var distance = countDownDate - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById(elementId).innerHTML = days + 'd ' +
hours + 'h ' +
minutes + 'm ' +
seconds + 's ';
if (distance < 0) {
clearInterval(x);
document.getElementById(elementId).innerHTML = "Expired";
}
}, 1000);
}
You need to use AJAX.
Example:
xhttp.open("POST", "path/to/post/handler.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Henry&lname=Ford");
In your case:
if (distance < 0) {
clearInterval(x);
document.getElementById(elementId).innerHTML = "Expired";
//this is where you update the database:
xhttp.open("POST", "path/to/post/handler.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//use the xhttp object to send(POST) values to the database.
xhttp.send("message=Expired&id=242");
}
More info Here
What are you using in the back end?
You will need to handle the JavaScript POST:
Example PHP would be:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $this->mysqli->prepare("UPDATE yourTable SET status=? WHERE id=?");
$stmt->bind_param('si', $_POST['message'], $_POST['id']);
$stmt->execute();
return $stmt->affected_rows;
$conn->close();
?>
Let me know in the comments if it works...

creating custom time algorith like timeago in javascript

I want a custom time algorithm like javascript. I was able to achieve this using php but am not able to do the same with javascript!
WHat i had in php was like.....
PHP FIDDLE(i want something like this in js output)
function getTime($mytime){
// $mytime is a datetime sql database format time
$thetime = strtotime($mytime);
$q = new DateTime($mytime);
$current_time = date('Y-m-d H:i:s',time());
$w = new DateTime($current_time);
$result = $w ->diff($q);
$string = "";
$year = $result->y;
$month = $result->m;
$day = $result->d;
$hour = $result->h;
$min = $result->i;
$sec = $result->s;
if($year==0){
if($month==0){
if($day==0){
if($hour==0){
if($min==0){
if($sec <30){
$string .= "Just now";}else if($sec<60){ $string .= "A few seconds ago";}
}else{
if($min<5){$string .="A few minutes ago";}else if($min>=5){$string .=$min . ' minutes ago'; }
}}else{
if($hour<6){$string .=$hour . ' hours ago';}else if($hour>=6){
$chour = (date('H',$thetime));
if( ($chour>=5)&&($chour<=17) ){$string .= 'Today at ' .date('h.m a',$thetime);}else{$string .= 'Tonight at '. date('h.m a',$thetime);}}
}}else{
if($day==1){$string .= "Yesterday at " . date('h:m a',$thetime);}else if(($day>1) && ($day<=7)){$string .= $day . " days ago";}else if($day>7){$string .= date('M, d',$thetime) . ' at '. date('h:i a',$thetime);}
}}else{
if($month<5){$string .=$month . ' months ago'; }else if($month>=5){$string .= date('M,d',$thetime) .' at ' . date('h.i a',$thetime) ;}
}}else{
$string .=date('dS M , Y',$thetime) .' at '. date('h.i a',$thetime);
}
return $string;
}
What i thought was to dynamically update time using javascript! so i did this......
$(function(){
var $second = 1000;
var $minute = $second * 60;
var $hour = $minute * 60;
var $day = $hour * 24;
setInterval(function(){
$('.comment').each(function(){
var $this = $(this);
var $time = new Date($this.attr('datetime'));
var $now = new Date();
var $distance = $now - $time;
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 $time_string = '';
if($days > 0) {
$time_string = $time_string + $days + ' Day(s) ';
}
if($hours > 0) {
$time_string = $time_string + $hours + ' Hour(s) ';
}
if($minutes > 0) {
$time_string = $time_string + $minutes + ' Minute(s) ';
}
if($seconds > 0) {
$time_string = $time_string + $seconds + ' Second(s)';
}
$this.text($time_string);
});
}, 1000);
});
but his outputs something like this fiddle here.
What i wanted is like my prev. php output i.e X min ago or X seconds ago or 12 May 2014 etc how do i implement my above php code with this js ?

Javascript countdown just working on Chrome

Well, I'm making a game, and in my game I have a countdown script in javascript that receives the date when the building upgrade is over, and makes a countdown, and when the countdown ends, executes a script that upgrades the building to the next level.
But just works in google chrome, and in the other browsers appears like that:
Firefox:
Google Chrome
Just the Javascript:
date_default_timezone_set('europe/lisbon');
$datephp = date('Y-m-d H:i:s');
echo'
<script type="text/javascript">
function cdtd() {
var xmas = new Date("' . $factory_date . '");
var now = new Date();
var timeDiff = xmas.getTime() - now.getTime();
if (timeDiff <= 0) {
clearTimeout(timer);
$("#factory_upgrade").load("/include/factory_upgraded.php");
$("#quantidade_fabricas").load("/include/factory_stats.php");
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;' .
"var tempo=('0' + hours).slice(-2)+':'+('0' + minutes).slice(-2)+':'+('0' + seconds).slice(-2);"
.
'
document.getElementById("secsBox").innerHTML = tempo;
var timer = setTimeout("cdtd()",1000);
}
</script>
';
Complete function:
function factory_update($get){
$userid = $_SESSION['userid'];
$query00 = "SELECT * FROM factory_upgrading WHERE userid = '$userid'";
$result00 = mysql_query($query00) or die(mysql_error());
while($row00 = mysql_fetch_array($result00)){
$factory_upgrade = $row00['userid'];
}
if(!isset($factory_upgrade)){
echo "Sem melhoramentos.";
return 0;
}
$query01 = "SELECT * FROM factory_upgrading WHERE userid = '$userid'";
$result01 = mysql_query($query01) or die(mysql_error());
while($row01 = mysql_fetch_array($result01)){
$factory_level = $row01['new_level'];
$factory_date = $row01['upgraded'];
}
if ($get == "load")
{
echo '<div class="message_upgrades" ">';
echo '<div class="loading"><img src="/images/loading.gif"></img></div>';
echo '</div>';}
else
{
date_default_timezone_set('europe/lisbon');
$datephp = date('Y-m-d H:i:s');
echo'
<script type="text/javascript">
function cdtd() {
var xmas = new Date("' . $factory_date . '");
var now = new Date();
var timeDiff = xmas.getTime() - now.getTime();
if (timeDiff <= 0) {
clearTimeout(timer);
$("#factory_upgrade").load("/include/factory_upgraded.php");
$("#quantidade_fabricas").load("/include/factory_stats.php");
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;' .
"var tempo=('0' + hours).slice(-2)+':'+('0' + minutes).slice(-2)+':'+('0' + seconds).slice(-2);"
.
'
document.getElementById("secsBox").innerHTML = tempo;
var timer = setTimeout("cdtd()",1000);
}
</script>
';
echo '<div class="success_upgrades">';
echo '<div class="upgrade_text"><b>Nivel: </b>' . $factory_level . '</div><div class="div_separator"></div><div class="upgrade_text"><b>Duração:</b>
<div class="secsBox" id="secsBox"></div>
<script type="text/javascript">cdtd();</script></div><div class="div_separator"></div>
';
echo '<div id="close" class="stop_upgrade" ></img></div>';
echo '</div>';
echo '<script>
$(".stop_upgrade").click(function (e) {
e.preventDefault();
$(factory_upgrade2).empty();
setTimeout(function(){
$("#factory_upgrade2").load("/include/upgrade_cancel.php");
$("#factory_upgrade").load("/include/factory_update.php");
$("#load").load("/include/cabecalho_content.php");
$("#industrial").fadeIn();
$(loader1).delay(1000).hide(0);
}, 100);
});
</script>
';
}
}
The format of $factory_date is invalid according to standard JavaScript and Chrome happens to be able to parse it.
For better results, stick to these Date constructors:
new Date();
new Date(value);
new Date(dateString);
new Date(year, month [, day, hour, minute, second, millisecond]);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Creating a dynamic javascript countdown timer

I'm looking to create a dynamic javascript countdown timer, I want to pass it a datetime variable from my SQL server database and have it count down to this date then display a message, I've tried nearly every JQuery plugin I can find and Havent been able to edit them to do what I need, I also need to be able to have multiple countdown timers on the same page,
Any help would be much appriciated
Cheers
Scott
=======EDIT=======
After much Trial and Error I was able to modify this js http://andrewu.co.uk/clj/countdown/pro/
to do what I needed
try this:
function Thick(startin) {
startin--;
document.getElementById('timer').innerHTML = startin;
if(startin > 0) setTimeout('Thick(' + startin + ')', 1000);
}
call thus function in body onLoad like:
<body onLoad="Thick(20);">
hope this help :)
//TODAY'S DATE
$today = time();
//FETCHES DATE AND TIME FOR THE EVENT FROM DATABASE
$sql = "SELECT * FROM post";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$Row = (mysqli_fetch_assoc($result));
$th = $Row['endtime'];
}
echo $th
first of all put it into a variable then use your javascript to call the variable
//let get todays date here
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 $th; ?>';
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 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('countdown').innerHTML = days + ":" + hours + ":" + minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer()', 1000);
</script>
the javascript call in the variable with '<?php echo $th; ?>'; then the javascript does the count down with out refreshing the page

Categories