I have this PHP countdown timer script, and I'm trying to have JQuery hide the timer when it reaches 0 days, 0 hours, 0 mins, 0 secs. I know the JQuery show() and hide() functions can be used here, however I am unaware of how to trigger those JQuery functions when the PHP countdown timer reaches 0.
PHP code:
$secs = strtotime("2013-06-23 17:00:00 +1 GMT") - time();
$days = floor($secs / 86400);
$secs %= 86400;
$hours = floor($secs / 3600);
$secs %= 3600;
$mins = floor($secs / 60);
$secs %= 60;
echo "<div class='value'>$days<br><p class='time'>Days</p></div>";
echo "<div class='value'>$hours<br><p class='time'>Hours</p></div>";
echo "<div class='value'>$mins<br><p class='time'>Mins</p></div>";
echo "<div class='value'>$secs<br><p class='time'>Secs</p></div>";
?>
JQuery I'm using:
$(document).ready(function(){
setInterval(function(){
$("#timer").load("date.php");
});
});
The countdown timer is displayed in this div:
<div id="timer"></div>
I've rewritten your code using JSON instead. Here it is:
HTML:
<div class="countdown">
<div class="days"><span>$days</span><br> <p>Days</p></div>";
<div class="hours"><span>$hours</span><br> <p>Hours</p></div>";
<div class="minutes"><span>$mins</span><br> <p>Mins</p></div>";
<div class="seconds"><span>$secs</span><br> <p>Secs</p></div>";
</div>
JS:
$.getJSON("date.php").done(function(data){
if(data.zero){
// timer is 0 so hide
$('.countdown').fadeOut();
}else{
$('.countdown').fadeOut(function(){
$(this).find('.days span').html(data.days);
$(this).find('.hours span').html(data.hours);
$(this).find('.minutes span').html(data.minutes);
$(this).find('.seconds span').html(data.seconds);
$(this).fadeIn();
});
}
}).fail(function(){
// if it fails this function will be called
});
PHP:
<?php
$json = array();
$json['seconds'] = strtotime("2013-06-23 17:00:00 +1 GMT") - time();
$json['days'] = floor($secs / 86400);
$json['seconds'] %= 86400;
$json['hours'] = floor($secs / 3600);
$json['seconds'] %= 3600;
$json['minutes'] = floor($secs / 60);
$json['seconds'] %= 60;
$json['zero'] = array_sum($json) > 0 ? false : true;
echo json_encode($json)
?>
As mentioned, you can use Javascript for this entirely.
If you do wish to use PHP + Javascript, you need to expand your timer callback to parse the time. Check this question for an example:
javascript: how to parse a date string
Once you parse the various parts of the time, you can then use hide() if the timer reaches zero.
With jQuery, you can parse the time parts like this:
var days = $("#timer .value").eq(0).html();
var hours = $("#timer .value").eq(1).html();
var mins = $("#timer .value").eq(2).html();
var secs = $("#timer .value").eq(3).html();
However, you will need to put the value itself in a separate div, i.e. something like:
echo "<div class='value'>$days</div><div><br><p class='time'>Days</p></div>";
echo "<div class='value'>$hours</div><div><br><p class='time'>Hours</p></div>";
echo "<div class='value'>$mins</div><div><br><p class='time'>Mins</p></div>";
echo "<div class='value'>$secs</div><div><br><p class='time'>Secs</p></div>";
This way, you can get the whole contents of the value div without breaking up the value it contains into chunks. If you absolutely must have everything in the same div, you can split the div contents with Javascript's split() function:
http://www.w3schools.com/jsref/jsref_split.asp
You could just hide it with jQuery... Something like this:
$(document).ready(function(){
if ($("#timer:contains('0 days, 0 hours, 0 mins, 0 secs')").length) {
$("#timer").hide();
}
});
Demo
Related
I'm designing a website where there is a little game going on. Each user that participates has 99 minutes to complete it otherwise we display a game over state. Here is what I managed to do so far using jQuery post.
I've been able to display the timer. In the PHP I've set the target time to 99*60 seconds but I cant set the starting time to 0 as I'll do the difference beteen those to values for the countdown.
Furthermore, as each user is able to quit the page I want to be able to store the time when they left. All I am able to do is store the countdown value, let's say 5845, in the DB when they log off. Though I tried updating the table with each call to the jQuery post, it just makes it worse.
Here is my jQuery:
function countdown() {
var i = (new Date().getTime() / 1000) + (99 * 60);
setTimeout(function () {
$.post(\'countdown.php\',{target:i},function(data){
$('#countdown').html(data);
});
countdown();
},1000);
}
countdown();
Here is the PHP:
if (!empty($resm['Countdown']) || $resm['Countdown'] >= 0) {
$target = (99 * 60);
$countdown = ($target - $current);
$_SESSION['currenttime'] = $countdown;
$hours = floor($countdown / 3600);
$min = floor($countdown / 60);
$r_min = floor(($countdown - ($hours * 3600)) / 60);
$sec = floor($countdown - ($min * 60));
if ($min == 0) {
echo $target.' '.$current.' '.$countdown;
echo '<br/>'.$min.' minutes '.$sec.' seconds left';
} else {
echo 'Time Over';
$sql = "UPDATE bs10000099 SET Upgradedlevel='2',Activated='2',Countdown='5940' WHERE MemberID='$memberid'";
mysql_query($sql);
}
}
I cant figure out how to set the starting time or how to prevent countdown() restart on refresh page.
I'm not sure what kind of security you want, but getting time from Javascript is not really secure since JS gets the time from the computer instead of the server.
With your example, I would be able to play the game, wait until there's 10 minute left, and just roll back time on my desktop and it will reset. Or roll back a year and have 100000 minutes left!
I suggest you use server time.
Here is what I would do:
When the test starts, get the UNIX time + 90 minutes. This will give you the final time.
PHP
if (!isset($_SESSION['end'])) {
$_SESSION['end'] = strtotime("+90 minutes");
}
$remaining = $_SESSION['end'] - time();
if ($remaining > 0) {
echo json_encode(array(
"remaining" => $remaining
));
} else {
// finished! write code here.
}
You can then do a simple $.getJSON() to get the remaining seconds and display it.
Since you kept the "end" time, even if the users leave, the timer will continue.
I need to build a countdown timer in jquery that replaces the html in a span tag from a php variable that's formatted to XX Days XX:XX:XX. It should load the variable on page load and then when the jquery script loads it starts the countdown but keeping the same format (XX Days XX:XX:XX) and eventually displays "Expired" and stops the countdown.
I have a jsFiddle started (http://jsfiddle.net/2SDdh/1/) but it shows the formatted time and then loads a 10 sec countdown and eventually shows "Expired". Anyone know how to get the formatting correct?
My HTML output via PHP
<span class="exp">10 Days 10:10:10</span>
My jQuery
$(function(){
var count = 10;
countdown = setInterval(function(){
if (count > 0) {
count--;
$(".exp").html(count);
} else {
$(".exp").html('Expired');
}
}, 1000);
});
try this
html:
<span class="days">10</span> Days <br />
<span class="exp">23:59:59</span>
javascript :
$(function(){
var days = 10;
var count = 86399;
var count2 = 0;
var hour = 0;
var min = 0;
var sec = 0;
countdown = setInterval(function() {
if (days != 0 || count != 0) {
if (count == 0) {
days--;
count = 86399;
} else {
count--;
}
count2 = count;
hour = Math.floor(count2 / 3600);
count2 = count2 % 3600;
min = Math.floor(count2 / 60);
count2 = count2 % 60;
sec = count2;
$(".exp").html(hour + ":" + min + ":" + sec);
$(".days").html(days);
} else {
$(".exp").html('Expired');
}
}, 1000);
});
Cheers!
Instead of rolling your own countdown timer, why not use one that already exists?. KK Countdown works well for me.
Note * I want some one to fix it and tell me how they did it not tips on how to do it or coments about php nd java mixed in it *
I have a countdown script that is working, but when it hits the target date the timer keeps on going to a negative time. I want it to stop on that target date and just display a finishing message. It's live on my site. I just need help editing the countdown script.
I want to keep the same layout. I need some help adding the finishing message and stopping it from going into the negative date, or just make it not display the 0days, 0 hours, 0mins, 0sec until the site's officially released. When that finally happens, I want it to display a message.
countdown script
<?php date_default_timezone_set('EST'); ?>
<?php
// Define your target date here
$targetYear = 2011;
$targetMonth = 9;
$targetDay = 1;
$targetHour = 20;
$targetMinute= 00;
$targetSecond= 00;
// End target date definition
// Define date format
$dateFormat = "Y-m-d H:i:s";
$targetDate = mktime($targetHour,$targetMinute,$targetSecond,$targetMonth,$targetDay,$targetYear);
$actualDate = time();
$secondsDiff = $targetDate - $actualDate;
$remainingDay = floor($secondsDiff/60/60/24);
$remainingHour = floor(($secondsDiff-($remainingDay*60*60*24))/60/60);
$remainingMinutes = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))/60);
$remainingSeconds = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))-($remainingMinutes*60));
$targetDateDisplay = date($dateFormat,$targetDate);
$actualDateDisplay = date($dateFormat,$actualDate);
?>
<script type="text/javascript">
var days = <?php echo $remainingDay; ?>
var hours = <?php echo $remainingHour; ?>
var minutes = <?php echo $remainingMinutes; ?>
var seconds = <?php echo $remainingSeconds; ?>
</script>
<body onLoad="setCountDown();">
<center><?php echo "$remainingDay days, $remainingHour hours, $remainingMinutes minutes and $remainingSeconds seconds";?> untill official release</center>
how its added on the site
<script type="text/javascript">
$(function() {
/* Union War */
$("#Countdown2").load("http://imperialism.zxq.net/includes/process/uwcountdown.php");
setInterval(function(){
$("#Countdown2").load("http://imperialism.zxq.net/includes/process/uwcountdown.php");
}, 1000);
});
</script>
<div id="uwCD" class="uwCD">
<div id="Countdown2"></div>
</div>
I recommend this jQuery countdown plugin; just pass the PHP value to the jQuery plugin call.
if($targetDate != $actualDate && $targetDate > $actualDate) {
echo "$remainingDay days, $remainingHour hours, $remainingMinutes minutes and $remainingSeconds seconds";
} else {
echo "0 days, 0 hours, 0 minutes and 0 seconds";
}
try using this http://www.timeanddate.com/counters/customcount.html everything is done for you and its worked fine and if anything you can just edit the look of the skin to fit your website
if($targetDate != $actualDate && $targetDate > $actualDate) {
echo "$remainingDay days, $remainingHour hours, $remainingMinutes minutes and $remainingSeconds seconds";
} else {
echo "0 days, 0 hours, 0 minutes and 0 seconds";
}
Im creating a website for my brothers wedding. And so far all is going well. However, he wants a countdown to the wedding on the homepage;
Time left until the wedding: X months, X days, X hours.
I would preferebly like to do this using php, but would be open to other suggestions.
if you can help me with ideas for the coding, or just point me to relevant material, that would be useful.
The wedding is on Saturday 30th July.
If your need your counter to be displayed only on page refresh and be static once the page is loaded, then PHP will be fine.
If you need the countdown to get refreshed when the page is displayed, you'll need to use JavaScript.
Personally I would go for something already implemented, like that small script.
Following is the code snippet I have copied from the W3Schools website, while added my PHP code to get the "countdown to" timestamp and the "now" timestamp.
You will see I have commented out the original JavaScript code and replaced it with PHP code in two places, so it's clear to tell what's the difference between two options.
Basically when you think the "server time" is more reliable in your case, you can adopt the PHP approach.
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
p {
text-align: center;
font-size: 60px;
margin-top: 0px;
}
</style>
</head>
<body>
<p id="demo"></p>
<script>
// Set the date we're counting down to
// 1. JavaScript
// var countDownDate = new Date("Sep 5, 2018 15:37:25").getTime();
// 2. PHP
var countDownDate = <?php echo strtotime('Sep 5, 2018 15:37:25') ?> * 1000;
var now = <?php echo time() ?> * 1000;
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
// 1. JavaScript
// var now = new Date().getTime();
// 2. PHP
now = now + 1000;
// Find the distance between now an 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("demo").innerHTML = days + "d " + hours + "h " +
minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
</body>
</html>
For Static Countdown :
<?php
//A: RECORDS TODAY'S Date And Time
$today = time();
//B: RECORDS Date And Time OF YOUR EVENT
$event = mktime(0,0,0,12,25,2006);
//C: COMPUTES THE DAYS UNTIL THE EVENT.
$countdown = round(($event - $today)/86400);
//D: DISPLAYS COUNTDOWN UNTIL EVENT
echo "$countdown days until Christmas";
?>
$wedding = strtotime("2011-07-01 12:00:00+0400"); // or whenever the wedding is
$secondsLeft = $wedding - time();
$days = floor($secondsLeft / 60*60*24);
$hours = floor(($secondsLeft - $days*60*60*24) / 60*60);
echo "$days days and $hours hours left";
Code top by user Neil E. Pearson didn´t work, he forgot to write there the brackets (), working solution is:
$wedding = strtotime("2011-07-01 12:00:00+0400"); // or whenever the wedding is
$secondsLeft = $wedding - time();
$days = floor($secondsLeft / (60*60*24)); // here the brackets
$hours = floor(($secondsLeft - ($days*60*60*24)) / (60*60)); // and here too
echo "$days days and $hours hours left";
$Target_Date = 1699458858; //expire data
$Time_Left = $Target_Date - time();
$days = floor($Time_Left / (60*60*24));//day
$Time_Left %= (60 * 60 * 24);
$hours = floor($Time_Left / (60 * 60));//hour
$Time_Left %= (60 * 60);
$min = floor($Time_Left / 60);//min
$Time_Left %= 60;
$sec = $Time_Left;//sec
echo "$days days and $hours hours and $min min and $sec sec left";
I would not use php (serverside) for this. Because you need to refresh your page every time to see the counting. Preferably use javascript (clientside) for this, more specific jquery (javascript framework). And look for a jquery plugin such as: http://keith-wood.name/countdown.html
If you want something realtime, you'll need to use client-side scripting, namely JavaScript.
You can do it in PHP, but it won't "animate":
$wedding = strtotime("2011-07-01 12:00:00+0400"); // or whenever the wedding is
$secondsLeft = $wedding - time();
$days = floor($secondsLeft / 60*60*24);
$hours = floor(($secondsLeft - $days*60*60*24) / 60*60);
echo "$days days and $hours hours left";
You could put some more math in for months, but it gets fuzzier because a month isn't a fixed amount of time.
The other way would be to use the date() function to pick out the individual elements (hour, minute, second, day, month etc) and use rollover math, but it's a lot of bother for a 'nice effect'.
Let me know if you want a JavaScript example. Don't bother with jQuery - it's a canon for killing a mosquito :)
try this
<?php
$target = mktime(0, 0, 0, 9, 25, 2011) ;//set marriage date
$today = time () ;
$difference =($target-$today) ;
$month =date('m',$difference) ;
$days =date('d',$difference) ;
$hours =date('h',$difference) ;
print $month." month".$days." days".$hours."hours left";
?>
Try this
$wedding = strtotime("2014-02-20 12:00:00"); // or whenever the wedding is
$current=strtotime('now');
$diffference =$wedding-$current;
$days=floor($diffference / (60*60*24));
echo "$days days left";
Try this static countdown.
<?php
//Current Date And Time
$todaytime = time();
//Set Date And Time OF The Event
$eventdate = mktime(0,0,0,0,28,2021);
//Calculate Days Until The Event
$countdown = round(($eventdate - $todaytime)/86400);
//Display Countdown
echo "$countdown days until the event";
?>
My project in php
I want to create a countdown timer for asking question in limited timeframe like LMS
here i have use the javascript countdown timer but when refresh the page javascript timer are reset.
You could store the start time in a php session. Then everytime you load a page you can continue the countdown timer with javascript, e.g.
<?php
//on every page
session_start();
//when you start
$_SESSION['start_time'] = time();
Then on every page:
<script type="text/javascript">
var startTime = <?php echo $_SESSION['start_time']; ?>;
//calculate remaining time
</script>
You will need to watch for when the timezones are different, or when the client's clock is wrong. Maybe instead you could calculate the remaining time in seconds and print that into javascript on each page, but then you could have innacuracy over high latency connections etc.
Try something like:
<?php
session_start();
//to reset the saved countdown
if (!empty($_REQUEST['resetCountdown']))
{
unset($_SESSION['startTime']);
}
if (empty($_SESSION['startTime']))
{
$_SESSION['startTime'] = time();
}
//In seconds
$startTime = time() - $_SESSION['startTime'];
?>
<script type="text/javascript">
var countdown = 60; //in seconds
var startTime = <?php echo $startTime; ?>;
startCountdown(startTime, countdown);
function startCountdown(startFrom, duration)
{
//countdown implementation
}
</script>
You could also store the timer in a session variable in PHP so that when the page is refreshed the time is still preserved.
try this
<script>
// Set the date we're counting down to
var countDownDate = new Date("Aug 1, 2017 12:00:00").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 an 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("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
and also put this under body tag.
<p id="demo"></p>