views:

199

answers:

6

Hi

I am doing online Exam Management, I have set a time duration for an exam to 5 min.

When student attend this test, timer starts decreasing.

I made this timer using javascript.

What the problem is if the student refresh the page timer starts from first. How can I make the time to be static if page refreshed.

+3  A: 

You cannot avoid the timer from resetting because when a page reload, all HTML and JS reloads. You can store the current time in a "cookie". Look up "Using cookies in Javascript".

The work flow would be as follows

  1. Page loads and you start a timer.
  2. User reloads the page.
  3. Listen for the onBeforeUnload (and onUnload) events in Javascript and write a cookie that stores the current time.
  4. When the page reloads back, read this time from the cookie and use that.
  5. When timer ends, be sure to clear the cookie.
Amit Behere
+2  A: 

The only things in javascript that would stay around between pages or page refreshes are cookies.

You could periodically set the cookie value to be the time left and check it on page load and start the timer at that value if its not 0.

BeaverProj
"he only things in javascript that would stay around between pages or page refreshes are cookies." - or AJAX values, essentially server-side cookies!
Moshe
True, you could even use session if you're getting AJAX involved.
BeaverProj
+1  A: 

You cant. However, you can do another thing, lets say less polite :

Use ajax to update the database saying that student X has already started the exam, and if it refreshes the page, read that value and blow his chances off ;)

yoda
+3  A: 

In short: Cookies or AJAX (PHP)

AJAX timer. Make a php page "remember" the time for the student and the javascript will tell the php to deduct the "second" or however long from the stored time.

Alternatively, try using a cookie.

1)Check if cookie exists

2) If not set the cookie to expire in 5 minutes from the start time. If yes, check if Cookie is expired.

3)If the cookie is expired, show "Time up" if not, keep waiting.

The problem is that Javascript can be run from the browser's address bar and as such is not really a good option in a secure test environment.

Moshe
+2  A: 

Make something like this in PHP:

<script type="text/javascript">
var remainingtime = <?php echo $remainingtime; /* remaining seconds */ ?>;
</script>

Then from JavaScript you could read the value of this variable.

EDIT: Later of course you have to check on the server side if the time is right, because the JavaScript value could be faked.

Hippo
What happens if student hit refresh button in the browser. How can i assign value to php variable at that time?
RSK
you have to store the end/start time (even for the check at the end)... every time the user refreshes the page you recalc the remaining time.
Hippo
+1  A: 

Run the timer server-side and poll it using AJAX.

cxfx