Harry Sinfield Harry Sinfield - 1 month ago 7
Javascript Question

Turn php countdown into javascript

On my php website I have many various countdowns. These are only updated when the user refreshes the page. I want to change it so that the countdown is continous.

I have found many javascript codes that perform this, however I'm unsure how to implement my php code into there script.

Please see below scripts:

My php function for timer:

function countup ($online){
global $time;

$difference=$online-$time;
$num = $difference/86400;
$days = intval($num);
$num2 = ($num - $days)*24;
$hours = intval($num2);
$num3 = ($num2 - $hours)*60;
$mins = intval($num3);
$num4 = ($num3 - $mins)*60;
$secs = intval($num4);

if($days != 0){echo"$days days, ";}
if($hours != 0){echo"$hours hours, ";}
if($mins != 0){echo"$mins minutes and ";}
echo"$secs seconds";
}


where I show the timer I have the following..
<?=countup($set[ends])?>


Ends = future unix timestamp.

The javascript countdown I came across was from http://keith-wood.name/countdown.html but I have no understanding of java and am not sure how to put $set[ends] into it!

All help would be greatly appreciated!

Answer

Considering, that you're loading all required scripts properly, here is what I would suggest:

PHP part

$ends = date("Y, n-1, j", $set[ends]); //covert your time stamp to the required format

**JavaScript Part **

<script type='text/javascript'>
  ( function( $ ) {
      $('#yourCountDownDIV').countdown({until: <?php echo $ends ?>});
  } )( jQuery );
</script>

Put the JavaScript part at the end of the HTML code just before the closing tag and after all your JavaScript files are loaded.