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...
Related
I am a beginner. I am trying to write a simple extension. The idea is running a countdown timer in background.js and display it in the popup.html. I write some code below.
background.js
function countdown() {
window.intervalId = setInterval(function() {
window.remaining_time -= 1000;
chrome.runtime.sendMessage(JSON.stringify(get_status()), function(response) {
console.log("Respond receive!");
})
}, 1000)
}
popup.js
chrome.runtime.onMessage.addListener(
function(msg, sender, sendResponse) {
console.log("message received: " + msg);
if (msg == "Background port started!") {
return;
}
let timer_status = JSON.parse(msg);
let remaining_time = timer_status.remaining_time;
let curr_mode = timer_status.curr_mode;
let timer_state = timer_status.timer_state;
var days = Math.floor(remaining_time / (1000 * 60 * 60 * 24));
var hours = Math.floor((remaining_time % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var mins = Math.floor((remaining_time % (1000 * 60 * 60)) / (1000 * 60));
var secs = Math.floor((remaining_time % (1000 * 60)) / 1000);
var countdown_str = "";
if (days > 0) {
countdown_str += days + " days ";
}
if (hours > 0) {
countdown_str += hours + " hours ";
}
if (mins > 0) {
countdown_str += mins + " mins ";
}
countdown_str += secs + " secs";
document.getElementById("countdown").innerHTML = countdown_str;
sendResponse({farewell:"Goodbye"});
}
)
The code running fine when the popup is open. However, when the popup is closed, the problem occured as "Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist".
I've looked for popup closing event but it seems not to exist. So my question is are there any ELEGANT way to continually send messages from background.js to popup.js in setInterval but only when the popup script is opened?
If the popup is not open this will fail and abort the execution of the sendresponse
document.getElementById("countdown").innerHTML = countdown_str;
sendResponse({farewell:"Goodbye"});
either use try
try{
var test= document.getElementById("countdown");
if(test){ test.innerHTML= countdown_str;}
}catch (ex){
console.log(ex);
console.log(typeof(test)); //also a possible way to check
}
or check it something like this
if(document.body.contains(document.getElementById('test'))){
alert('Element exists!');
} else{
alert('Element does not exist!');
}
I have 2 coupons showing, they both have the .new-coupon when in fact one should say .new-coupon and one should say .old-coupon. It seems to apply the same class for every element on the page with that class instead of calculating which class it should be for each element.
jQuery(document).ready(function($) {
// Set the date we're counting down to
var deadlineYear = $("#clockdiv .year").attr("rel");
var deadlineMonth = $("#clockdiv .month").attr("rel");
var deadlineDay = $("#clockdiv .days").attr("rel");
var deadlineHour = $("#clockdiv .hours").attr("rel");
var deadlineMinute = $("#clockdiv .minutes").attr("rel");
var deadlineSecond = $("#clockdiv .seconds").attr("rel");
var couponExpired = $("#clockdiv").attr("rel");
var countDownDate = new Date(deadlineYear + "/" + deadlineMonth + "/" + deadlineDay + " " + deadlineHour + ":" + deadlineMinute + ":" + deadlineSecond).getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
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);
// Output the result in an element with id="demo"
document.getElementById("days").innerHTML = days;
document.getElementById("hours").innerHTML = hours;
document.getElementById("minutes").innerHTML = minutes;
document.getElementById("seconds").innerHTML= seconds;
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("clockdiv").innerHTML = "<p>" + couponExpired + "</p>";
}
var startDate = $("#clockdiv .start").attr("rel"); //2018/09/28 17:00:00
var startDateNew = new Date(startDate);
var newOldDate = new Date(startDateNew.setDate(startDateNew.getDate() + 7));
var nowDateNew = new Date(now);
if (days <= 7) {
$('.couponDiv').addClass("old-coupon");
} else if ((nowDateNew.getTime() - newOldDate.getTime()) < 0) {
$('.couponDiv').addClass("new-coupon");
}
}, 1000);
});
HTML used for variables:
<div id="clockdiv" rel="'.$expired.'">
<span class="start" rel="'.$start.'"></span>
<span class="year" rel="'.$year.'"></span>
<span class="month" rel="'.$month.'"></span>
<div><span id="days" class="days" rel="'.$day.'"></span><div class="smalltext">Days</div></div>
<div><span id="hours" class="hours" rel="'.$hour.'"></span><div class="smalltext">Hours</div></div>
<div><span id="minutes" class="minutes" rel="'.$minute.'"></span><div class="smalltext">Minutes</div></div>
<div><span id="seconds" class="seconds" rel="'.$second.'"></span><div class="smalltext">Seconds</div></div>
</div>
HTML used for displaying the coupons on the offers page:
<li>
<?php
$year = DateTime::createFromFormat('Y-m-d H:i:s', get_field('offer_voucher_deadline'))->format('Y');
$month = DateTime::createFromFormat('Y-m-d H:i:s', get_field('offer_voucher_deadline'))->format('m');
$day = DateTime::createFromFormat('Y-m-d H:i:s', get_field('offer_voucher_deadline'))->format('d');
$hour = DateTime::createFromFormat('Y-m-d H:i:s', get_field('offer_voucher_deadline'))->format('H');
$minute = DateTime::createFromFormat('Y-m-d H:i:s', get_field('offer_voucher_deadline'))->format('i');
$second = DateTime::createFromFormat('Y-m-d H:i:s', get_field('offer_voucher_deadline'))->format('s');
$humanDate = DateTime::createFromFormat('Y-m-d H:i:s', get_field('offer_voucher_deadline'))->format('D jS M Y');
$expiredText = get_field('offer_voucher_expired');
?>
<div style="display:none;">
<?php echo do_shortcode('[gw-countdown expired="'.$expiredText.'" year="'.$year.'" month="'.$month.'" day="'.$day.'" hour="'.$hour.'" minute="'.$minute.'" second="'.$second.'" start="'.get_field('offer_voucher_start').'"]');?>
</div>
<div id="couponDiv" class="couponDiv">
<h1><?php the_title();?></h1>
<div class="couponDetails">
<div class="couponView">
<?php $offer = get_field('offer_single_label', 'options'); $offerC = ucwords($offer);?>
<a class="button" href="<?php the_permalink();?>" title="See Offer Details">See <?php echo $offerC;?> Details</a>
</div>
<div class="couponValid">
<p class="bold">Valid Until:</p>
<p class="couponDate"><?php echo $humanDate;?></p>
</div>
</div>
</div>
</li>
Edit
I understand completely where the issue lies, and have updated the code to the following:
$('.couponDiv').each(function() {
var startDate = $("#clockdiv .start").attr("rel"); //2018/09/28 17:00:00
var startDateNew = new Date(startDate);
var newOldDate = new Date(startDateNew.setDate(startDateNew.getDate() + 7));
var nowDateNew = new Date(now);
if (days <= 7) {
$(this).addClass("old-coupon");
} else if ((nowDateNew.getTime() - newOldDate.getTime()) < 0) {
$(this).addClass("new-coupon");
}
});
However, I do not know how to make:
var startDate = $("#clockdiv .start").attr("rel");
Apply to $this so its $this #clockdiv .start because then it will work I believe...
Edit
I have altered a line of code to read:
var startDate = $(this).find("#clockdiv .start").attr("rel");
This now only adds the class to the first offer and not the 2nd offer, I then tried repeating the:
$(this).find()
Around the initial variables and then moved the:
$('.couponDiv').each(function() {
To the top below the document ready function however, this stopped any class being added.
if (days <= 7) {
$('.couponDiv').addClass("old-coupon");
} else if ((nowDateNew.getTime() - newOldDate.getTime()) < 0) {
$('.couponDiv').addClass("new-coupon");
}
In your codes above, you had selected all of .couponDiv to add class old-coupon and once again you select all of .couponDiv to add class new-coupon. The conditions have no meaning here because with any matching you still add class for all elements.
You must separate which elements are belong to "old" and with elements are belong to "new". Then add the respectively class name.
Is this what you need?
var startDate = $(this).find("#clockdiv .start").attr("rel"); //2018/09/28 17:00:00
After some reconstructing and work with $this I was able to get this working:
$('.couponWrap .coupons li').each(function() {
// Set the date we're counting down to
var deadlineYear = $(this).find("div .clockdiv .year").attr("rel");
var deadlineMonth = $(this).find("div .clockdiv .month").attr("rel");
var deadlineDay = $(this).find("div .clockdiv .days").attr("rel");
var deadlineHour = $(this).find("div .clockdiv .hours").attr("rel");
var deadlineMinute = $(this).find("div .clockdiv .minutes").attr("rel");
var deadlineSecond = $(this).find("div .clockdiv .seconds").attr("rel");
var couponExpired = $(this).find("div .clockdiv").attr("rel");
var countDownDate = new Date(deadlineYear + "/" + deadlineMonth + "/" + deadlineDay + " " + deadlineHour + ":" + deadlineMinute + ":" + deadlineSecond).getTime();
var startDate = new Date($(this).find("div .clockdiv .start").attr("rel"));
var self = $(this);
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
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);
// Output the result in an element with id="demo"
document.getElementById("days").innerHTML = days;
document.getElementById("hours").innerHTML = hours;
document.getElementById("minutes").innerHTML = minutes;
document.getElementById("seconds").innerHTML= seconds;
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("clockdiv").innerHTML = "<p>" + couponExpired + "</p>";
}
//Works but only for 1st start date
//var testDate = $("div .clockdiv .start").attr("rel"); //2018/09/28 17:00:00
var startDateNew = new Date(startDate);
var startDateNewer = new Date(startDate);
var newOldDate = new Date(startDateNewer.setDate(startDateNew.getDate() + 7));
//alert(startDate + ", " + startDateNew + ", " + startDateNewer + ", " + newOldDate);
//This works fine
var nowDateNew = new Date().getTime();
//alert(nowDateNew - newOldDate.getTime());
if (days <= 7) {
self.find('div.couponDiv').addClass("old-coupon");
} else if ((nowDateNew - newOldDate.getTime()) < 0) {
self.find('div.couponDiv').addClass("new-coupon");
}
}, 1000);
});
I have this code which works very well. But I wanted use mysql.
Here is the code that works:
<?php if (date('w') == 2) { { ?>
<script> $(function() {
var times = [
// mysql import start
{'id': '1', 'name': 'Mardi 5H55', 'end': new Date('2017-01-31 05:55:00'),},
{'id': '2', 'name': 'Mardi 8H40', 'end': new Date('2017-01-31 08:40:00'),},
{'id': '3', 'name': 'Mardi 11H30', 'end': new Date('2017-01-31 11:30:00'),},
{'id': '4', 'name': 'Mardi 14H05', 'end': new Date('2017-01-31 14:05:00'),}
// mysql import end
];
// Initialize the table values
$.each(times, function( key, value ) {
$('#mau-mpl').append('<tr><td>'+value.name+'</td><td>Hérault Transports (Ruban Bleu)</td><td>Montpellier</td><td><span id="player-'+value.id+'-expiration" class="label label-primary">Chargement encours...</span></td></tr>');
});
function countdown()
{
var now = new Date();
console.log('updating time');
$.each(times, function( key, value ) {
var left = value.end - now;
var days = Math.floor( left / (1000 * 60 * 60 * 24) );
var hours = Math.floor( (left % (1000 * 60 * 60 * 24) ) / (1000 * 60 * 60) );
var minutes = Math.floor( (left % (1000 * 60 * 60)) / (1000 * 60) );
var seconds = Math.floor( (left % (1000 * 60)) / 1000 );
displayTime = '';
if (days > 0) {
displayTime = + days + " jr ";
}
if (minutes > 0) {
displayTime = displayTime + hours + " H " + minutes + " Mn " + seconds + " Sec ";
}
echo = "Deja parti";
$('#player-'+value.id+'-expiration').text(displayTime)
});
}
timer = setInterval(countdown, 1000);
});</script><?php } } ?>
As you see my data that I want to put is after mysql import start.
I made a php file that fetches data from mysql and I have this result:
{'id': '1', 'name': 'Mardi 5H', 'end': new Date('2017-01-31 05:00:00'),},
{'id': '2', 'name': 'Mardi 6H', 'end': new Date('2017-01-31 06:00:00'),},
{'id': '3', 'name': 'Mardi 7H', 'end': new Date('2017-01-31 07:00:00'),},
The php file is:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "horaires";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
$sql = "SELECT id, jourheure, name, depart, arrivee FROM 2_mardi";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// {'id': '1', 'name': '5H', 'end': new Date('2017-01-31, 05:55:00'),},";
echo "{'id': '" . $row["id"]. "', 'name': '" . $row['name'] ."', 'end': new Date('" . $row["jourheure"]. "" . $row["depart"]. "'),},<br>"; }
} $conn->close();
?>
+---+----------+---------------------+
| 1 | Mardi 5H | 2017-01-31 05:00:00 |
+---+----------+---------------------+
| 2 | Mardi 6H | 2017-01-31 06:00:00 |
+---+----------+---------------------+
| 3 | Mardi 7H | 2017-01-31 07:00:00 |
+---+----------+---------------------+
How do I put the result in javascript variable between "mysql import start" and "mysql import end" ?
You can do this :
var js = <?php echo "{'id': '" . $row["id"]. "', 'name': '" . $row['name'] ."', 'end': new Date('" . $row["jourheure"]. "" . $row["depart"]. "')}"; ?>
But warning, I remove bad characters on your object at the last :
echo "{'id': '" . $row["id"]. "', 'name': '" . $row['name'] ."', 'end': new Date('" . $row["jourheure"]. "" . $row["depart"]. "'),},<br>"; }
---------------------------------------------------------------------------------------------------------------------------------^-^^^^^
You can set var with a lot diferent ways ,ajax,embebed javascript code inside php code...
When you want get a PHP object or var to javascript you need serialized the object to JSON in your php code, then you need set your JSON string and convert this string to a valid javascript object.
JSON is a string like this
"{'propertyname':'stringvalue','property2':true,'property3':null,'property':[...]}"
If now you can parse JSON on javascript code block
index.php
<?php
$result = getData() // your data like you want =>[ multiple objects ]
$resultJSON = json_encode($result); // "[{..},{...}]"
?>
<script>
var jsondata = parse.JSON('<?php echo $resultJSON ?>') ;
</script>
But i think is better slice the html/javascript code from php code, and get vars from ajax for example.
You can use AJAX call to a PHP script to store the data into Javascript variables.
In the following file the AJAX call using JQuery is demonstrated to store the data into Javascript
<?php if (date('w') == 2) { { ?>
<script>
$(function() {
var times = $.ajax({
url: 'api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
return data;
}
});
$.each(times, function(key, value) {
$('#mau-mpl').append('<tr><td>' + value.name + '</td><td>Hérault Transports (Ruban Bleu)</td><td>Montpellier</td><td><span id="player-' + value.id + '-expiration" class="label label-primary">Chargement encours...</span></td></tr>');
});
function countdown() {
var now = new Date();
console.log('updating time');
$.each(times, function(key, value) {
var left = value.end - now;
var days = Math.floor(left / (1000 * 60 * 60 * 24));
var hours = Math.floor((left % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((left % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((left % (1000 * 60)) / 1000);
displayTime = '';
if (days > 0) {
displayTime = +days + " jr ";
}
if (minutes > 0) {
displayTime = displayTime + hours + " H " + minutes + " Mn " + seconds + " Sec ";
}
echo = "Deja parti";
$('#player-' + value.id + '-expiration').text(displayTime)
});
}
timer = setInterval(countdown, 1000);
});
});</script><?php } } ?>
Following is the code which fetches the data from the database.
Let's call this file api.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "horaires";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, jourheure, name, depart, arrivee FROM 2_mardi";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
//storing result into an array
$array = mysql_fetch_row($result);
}
$conn->close();
//encoding the array into JSON
echo json_encode($array);
?>
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
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.