tags:

views:

273

answers:

4

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.

A: 

Save the actual time via ajax in an database...

Tobiask
That's an over-complicated approach that adds HTTP requests.
David Dorward
This is a terrible answer and any one of the other 3 answers here are more helpful and to the point
shambleh
A: 

You could also store the timer in a session variable in PHP so that when the page is refreshed the time is still preserved.

shambleh
+3  A: 

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.

Tom Haigh
+1  A: 

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>
inakiabt