Im creating a WP plugin for some quizzes, the problem is that each question has a timer, and with JavaScript I’m trying to push the user to the next question if the user doesn’t answer the question during the given timeframe. I already tried to ask ChatGPT but I’m just unable to understand the error. The JavaScript console doesn’t display any error. So far if the timer reached 0 seconds, it “submits” the form but it only refreshes the page, resets the counter and doesn’t display the next question, however if I manually click the “Next” button it submits the question and goes to the next question.
This is my code:
echo '<form method="post" action="" id="quiz-form">';
echo '<div>';
echo '<p>' . esc_html($current_question->question_text) . '</p>';
switch ($current_question->question_type) {
case 'radio_button':
$options = explode(',', $current_question->answer_options);
foreach ($options as $option) {
echo '<label><input type="radio" name="user_answer" value="' . esc_attr(trim($option)) . '"> ' . esc_html(trim($option)) . '</label><br>';
}
break;
case 'dropdown':
$options = explode(',', $current_question->answer_options);
echo '<select name="user_answer">';
foreach ($options as $option) {
echo '<option value="' . esc_attr(trim($option)) . '">' . esc_html(trim($option)) . '</option>';
}
echo '</select>';
break;
case 'multiple_options':
$options = explode(',', $current_question->answer_options);
foreach ($options as $option) {
echo '<label><input type="checkbox" name="user_answer[]" value="' . esc_attr(trim($option)) . '"> ' . esc_html(trim($option)) . '</label><br>';
}
break;
case 'free_question':
echo '<input type="text" name="user_answer" maxlength="500">';
break;
}
echo '</div>';
echo '<input type="hidden" name="question_id" value="' . $current_question->question_id . '">';
echo '<input type="hidden" name="is_timer_expired" value="0" id="is_timer_expired">';
echo '<input type="submit" name="qw_submit_quiz" value="Next">';
echo '</form>';
if ($current_question->question_timer) {
echo '<p>Time allowed: <span id="timer">' . esc_html($current_question->question_timer) . '</span> seconds</p>';
echo '<script>
let timeLeft = ' . intval($current_question->question_timer) . ';
let timer = document.getElementById("timer");
let quizForm = document.getElementById("quiz-form");
let countdown = setInterval(function() {
if (timeLeft <= 0) {
clearInterval(countdown);
document.getElementById("is_timer_expired").value = "1";
quizForm.submit();
} else {
timer.innerHTML = timeLeft;
}
timeLeft -= 1;
}, 1000);
</script>';
}
Expecting to go to the next question when timer reaches 0 seconds