Tuesday, June 12, 2012

Online quiz timer using JavaScript and PHP



To Design an online quiz timer using JavaScript and PHP:

1) To create a table to store  timer in minutes
CREATE TABLE  `cnsh_lms`.`edu_tests_extra` (
  `test_id` mediumint(8) unsigned NOT NULL auto_increment,
`timer` tinyint(4) unsigned NOT NULL,
`num_timer` bigint(10) unsigned NOT NULL default '0',
  PRIMARY KEY  (`test_id`)
) ENGINE=MyISAM AUTO_INCREMENT=82 DEFAULT CHARSET=utf8;

  2)  To display a count down timer, the initialized  minutes  from $row_2['num_timer']  in above table. When down to 0, the form quiz is submitted.
 <div style="font-weight: bold" id="quiz-time-left"></div>
<script type="text/javascript">
var max_time = <?php echo $row_2['num_timer'] ?>;
var c_seconds  = 0;
var total_seconds =60*max_time;
max_time = parseInt(total_seconds/60);
c_seconds = parseInt(total_seconds%60);
document.getElementById("quiz-time-left").innerHTML='Time Left: ' + max_time + ' minutes ' + c_seconds + ' seconds';
function init(){
document.getElementById("quiz-time-left").innerHTML='Time Left: ' + max_time + ' minutes ' + c_seconds + ' seconds';
setTimeout("CheckTime()",999);
}
function CheckTime(){
document.getElementById("quiz-time-left").innerHTML='Time Left: ' + max_time + ' minutes ' + c_seconds + ' seconds' ;
if(total_seconds <=0){
setTimeout('document.quiz.submit()',1);
   
    } else
    {
total_seconds = total_seconds -1;
max_time = parseInt(total_seconds/60);
c_seconds = parseInt(total_seconds%60);
setTimeout("CheckTime()",999);
}

}
init();
</script>

3) If you click refresh or go to another webpages, the for will be submitted auotomatically
<script type="text/javascript">
 function finishpage()
{
alert("unload event detected!");
document.quiz.submit();
}
window.onbeforeunload= function() {
setTimeout('document.quiz.submit()',1);
}
</script>

4. The form
 <form method="post" name="quiz" id="quiz_form" action="take_test1.php" >
</form>

11 comments: