Friday, November 30, 2012

Pass Javascript timer to HTML, form and PHP



 Below is the example to pass Javascript  timer to HTML, form and PHP
 Using document.getElementById("quiz-time-left").innerHTML=
to pass value to HTML
 <div style="font-weight: bold" id="quiz-time-left"></div>
We can use
 document.quiz.time_spent.value = total_seconds;
to pass value to  form
<input type="text" name="time_spent">
or
<input type="hidden" name="time_spent">
then can be transferred to php via $_POST['timne_spent']
Example code:
<div style="font-weight: bold" id="quiz-time-left"></div>
<form method="post" name="quiz" id="quiz_form" action="take_test1.php">
<input type="text" name="time_spent">
<input type="submit" class="input-button" name="submit1" value="Submit Test" />
</form>
<script type="text/javascript">
//var ts = Math.round((new Date()).getTime() / 1000);
//var ts = <?php echo time() ?>;
var max_time = <?php echo $row_2['num_timer'] ?>;
//var t0=<?php echo $_SESSION['t_start'] ?>;
var c_seconds  = 0;
//var total_seconds =60*max_time+t0-ts;
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';
document.quiz.time_spent.value = total_seconds;
function init(){
document.getElementById("quiz-time-left").innerHTML='Time Left: ' + max_time + ' minutes ' + c_seconds + ' seconds';
document.quiz.time_spent.value = total_seconds;
setTimeout("CheckTime()",999);
}
function CheckTime(){
document.getElementById("quiz-time-left").innerHTML='Time Left: ' + max_time + ' minutes ' + c_seconds + ' seconds' ;
document.quiz.time_spent.value = total_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();
function finishpage()
{
alert("unload event detected!");
document.quiz.submit();
}
//window.onunload =document.quiz.submit();
window.onbeforeunload= function() {
setTimeout('document.quiz.submit()',1);
}
</script>

No comments:

Post a Comment