I'm trying to make a timer that will be auto-submit all the answers when times up. But now, it just shows that the time is expired and it is not redirecting to the final score page.My answers are stored in the database, i dont think it is related. Here is the code :
$(document).ready(function() {
var endTime = localStorage.getItem("endTime");
console.log(endTime);
if (endTime != 'underfined' && endTime != null) {
startCountdownTimer();
//localStorage.removeItem("endTime");
}
});
function setEndTime() {
var currentTime = new Date().getTime();
var endTime = new Date(currentTime + 1*60000);
localStorage.setItem("endTime", endTime);
// alert('Set end time ' + endTime);
startCountdownTimer();
}
function startCountdownTimer() {
// Set the date we're counting down to
var endTime = localStorage.getItem("endTime");
var countDownDate = new Date(endTime).getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is finished,[ I want to make it is redirecting to score page ]
if (distance <= 0) {
clearInterval(x);
setTimeout("document.quiz.submit()",1);
window.location = "http://localhost/quizzer%202/final.php"
}
},1000);
}
Here's a solution with JavaScript's native setTimeout
function to auto-submit your form:
// The following ($function() {}) is equivalent to $(document).ready(function() {.
$(function() {
setTimeout(function() {
setTimeout(function() {$('#idOfYourForm').submit()},1);
window.location = "http://localhost/quizzer%202/final.php"
}, 1000 * 60 * 10); // This is the amount of milliseconds your test will last. I set this to ten minutes
});
Also, it doesn't look like the submit command is correct. Since you're using jQuery, I'll show you the jQuery way.
$('#idOfYourForm').submit()
(one problem was that you put quotation marks around it)One last thing, when you submit a form, the default action is that you will be redirected, so your last redirect won't do anything. For what you did to work, consider using AJAX. See this post.