Countdown timer built on PHP and jQuery?

After spending the last 45 minutes looking around for a solution, I can't seem to find an easy solution to creating a countdown timer using PHP and jQuery. Most already built scripts I've found are based purely on jQuery which require a ton of code, and more parameters then they should, plus, adaptability is pretty hard.

Here's my situation;

PHP:

$countdown = date("h:i:s"); // This isn't my actual $countdown variable, just a placeholder

jQuery:

$(document).ready(function name() {
    $("#this").load( function() {  
        setTimeout("name()", 1000)
      }
    }
});

HTML:

<div id="this"><?php echo($countdown); ?></div>

My idea is that, every second, #this is reloaded, giving a new value to it's contents, and as $countdown isn't a static variable, a new value will be loaded each time. This removes the need to deal with sessions (as a basic javascript countdown timer would reset on pageload, etc).

I would've though this would have worked, until I realized that the event binder .load() doesn't reload #this (I know silly me), so I guess what I'm wondering is - is there an event binder I can use to make this work or is there a way to get the functionality I'm looking for, without using a jQuery plugin (which doesn't match exactly what I want anyway)?

Answers:

Answer

You should use Keith Wood's countdown timer: http://keith-wood.name/countdown.html

It is extremely easy to use.

All you have to do is

$('#timer').countdown({
    until: '<?php echo date("h:i:s"); ?>' // change this, obviously
});

Here's the fiddle: http://jsfiddle.net/tqyj4/289/

Answer

OK, I know that an id is not a variable, but don't use this as an ID. It is makes people cringe.

To the rest, don't reload the value, set a value in JS in PHP and then count down.

// place this in the <head> above the code below
echo "var t = " . time() . ";";
echo "var ft = " . /* your final time here */ . ";";

Then:

// this is a helper function.
function lpad( input, len, padstr )
{
    if( !padstr ) padstr = " "; // this is the normal default for pad.
    var ret = String( input );
    var dlen = ret.length - len;
    if( dlen > 0 ) return ret;
    for( var i = 0; i < dlen; i++ ) ret = padstr + ret;
    return ret;
}

$(document).ready(function name() {
    $("#timer").load( function() {  // I changed the id
        $timer = $("timer"); // might as well cache it.
        // interval, not timeout. interval repeats
        var intval = setInterval(function(){
             t += 500; // decrease the difference in time
             if( t >= ft )
             {    
                 t = ft; // prevent negative time.
                 clearInterval( intval ) // cleanup when done.
             }
             var dt = new Date(ft - t); 
             $timer.innerHTML = dt.getHours() + ":" + 
                                // pad to make sure it is always 2 digits
                                lpad( dt.getMinutes(), 2, '0' ) + ":" + 
                                lpad( dt.getSeconds(), 2, '0' );
        }, 500) // increments of .5 seconds are more accurate
      }
    }
});
Answer

Once php has loaded a particular amount of time for the user, can you explain why this wouldn't be sufficient for your needs:

$(function(){
  $timerdiv = $("#this");

  timer();
});

function timer()
{
 $timerdiv.html((int)$timerdiv.html() - 1);
 setTimeout(timer, 1000);
}
Answer

You are very close in your original code. Here's a modification to your code below that works as described, or at least so I think - I know it works, but am not sure if it meets your requirements, they were a little unclear. Obviously if you reload the page, you would have to rely on the PHP output to be different in order for the counter to not reset. Just to note though, I'm not entirely sure why you would use the .load function - that function is really just a wrapper for an AJAX call to grab the contents of another page and insert it into the selected div. I believe what you're looking for is the .html() function to change the contents of the selected div using the content available in the DOM vs. making an AJAX request.

var timer;
$(document).ready(
    name();
);
function name() {
    //clear the timer
    clearTimeout(timer);
    //reset the timer
    timer = setTimeout("name()", 1000);
    //grab the current time value in the div
    var time = $("#this").html();
    //split times
    var time_splits = time.split(":");
    //add up total seconds
    var total_time = (parseInt(time_splits[0])*60*60) + (parseInt(time_splits[1])*60) + parseInt(time_splits[2]);
    //subtract 1 second from time
    total_time -= 1;
    //turn total time back in hours, minutes, and seconds
    var hours = parseInt(total_time / 3600);
    total_time %= 3600;
    var minutes = parseInt(total_time / 60);
    var seconds = total_time % 60;
    //set new time variable
    var new_time = (hours < 10 ? "0" : "") + hours + (minutes < 10 ? ":0" : ":" ) + minutes + (seconds < 10 ? ":0" : ":" ) + seconds;
    //set html to new time
    $("#this").html(new_time);
}
Answer
$dateFormat = “d F Y — g:i a”;
$targetDate = $futureDate;//Change the 25 to however many minutes you want to countdown change date in strtotime
$actualDate = $date1;
$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));

$actualDateDisplay = date($dateFormat,$actualDate);
$targetDateDisplay = date($dateFormat,$targetDate);

<script type=”text/javascript”>
var days = <?php echo $remainingDay; ?>
var hours = <?php echo $remainingHour; ?>
var minutes = <?php echo $remainingMinutes; ?>
var seconds = <?php echo $remainingSeconds; ?>

function setCountDown(statusfun)
{//alert(seconds);
var SD;
if(days >= 0 && minutes >= 0){
var dataReturn =  jQuery.ajax({
type: “GET”,
url: “<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB).’index.php/countdowncont/’; ?>”,
async: true,
success: function(data){
var data = data.split(“/”);
day =  data[0];
hours =  data[1];
minutes =  data[2];
seconds =  data[3];

}
});
seconds–;
if (seconds < 0){
minutes–;
seconds = 59
}
if (minutes < 0){
hours–;
minutes = 59
}
if (hours < 0){
days–;
hours = 23
}
document.getElementById(“remain”).style.display = “block”;
document.getElementById(“remain”).innerHTML = ” Your Product Reverse For “+minutes+” minutes, “+seconds+” seconds”;
SD=window.setTimeout( “setCountDown()”, 1000 );
}else{
document.getElementById(“remain”).innerHTML = “”;
seconds = “00?; window.clearTimeout(SD);
jQuery.ajax({
type: “GET”,
url: “<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB).’index.php/countdown/’; ?>”,
async: false,
success: function(html){

}
});
document.getElementById(“remain”).innerHTML = “”;
window.location = document.URL; // Add your redirect url

}
}
</script>

<?php
if($date1 < $futureDate &&  ($qtyCart > 0)){ ?>
<script type=”text/javascript”>
setCountDown();
</script>
<?php }else{ ?>
<style>

#remain{display:none;}
</style>
<?php }}?>
<div id=”remain”></div>

For more information visit urfusion

Answer

@epascarello answer for your question in you need to pass the loop value in selector with id for example $("#timer<? php echo $loopval; ?>")

and also call the it in the

<div id="timer<?php echo $loopval; ?>">
</div> 

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.