Search code examples
javascriptphphtmlforms

How can I stop submitting a form on page refresh in html?


Consider that I have a form like this:

<form method="get" action=<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?> style='margin:auto;text-align:center' id="send" >
<input type="hidden" name="questionid" value="<?php echo $questionid ?>" />
<input type="hidden" name="answered" value='true'>
<input id='submitbtn' type="button" <?php if($answered=='true')echo "style='display:none'";?> onclick="send()" value="SUBMIT">
</form>

Actually, I am creating an exam-based website. What I am trying to do is, if the user clicks the submit button, the function send() is triggered and the form is submitted:

function send(){    
document.getElementById('send').submit();
<?php 
$answered="true";
if(isset($_COOKIE["upstr"]))
$updata=$_COOKIE["upstr"];
else $updata="";
$upsql="UPDATE question_data SET answered='$answered', ansstr='$updata', timespnt='$timetaken' WHERE questionid='$questionid'";
$conn->execute_query($upsql);
?>
    document.cookie="upstr=''; expires=Thu, 01 Jan 1970 00:00:00 UTC;"
}

Here upstr is a simple cookie that stores the values that the user has clicked to validate later. Here the php variable $answered turns true from false as the form is submitted.

What I am facing as the problem is, the user, if for any reason, reloads the page, the form is submitted. I was also storing the time the user required to solve the question and stores it as the php variable $timespnt but it does not work too. I think my problem is that the form gets submitted on pressing the refresh page button. Any idea on how to solve it? Or am I facing something different?

Edit: This is what have tried finally...

<html>
<head>
<script>
    
var Timer;
var TotalSeconds;
<?php
$time=6;
$length=1;
$timetaken=6*$length-$time;
$questionid=7;
$answered="false";
$servername = "****";
$dbusername = "****";
$dbpassword = "****";
$dbname= "****";
$conn = mysqli_connect($servername, $dbusername, $dbpassword, $dbname);
?>
function CreateTimer(TimerID, Time) {
    Timer = document.getElementById(TimerID);
    TotalSeconds = Time;
    UpdateTimer();
    console.log(TotalSeconds);
    window.setTimeout("Tick()", 1000);}

function Tick() {
    TotalSeconds -= 1;
    if(TotalSeconds==0){
        <?php $answered="true";?>
        document.cookie="timer="+TotalSeconds+"expires=Thu, 01 Jan 1970 00:00:00 UTC;";
    }

    else{
    UpdateTimer()
    window.setTimeout("Tick()", 1000);
}
}

function UpdateTimer() {
Timer.innerHTML = TotalSeconds;
document.cookie="timer="+TotalSeconds;}
</script>
</head>
<body>
<?php echo $answered;?>
<!--Outputs "true" here but why?-->
<div id='timer'></div>

<?php 
if (isset($_REQUEST["submitButton"]) || isset($_REQUEST["submitted"])){
  $answered="true";
  $updata=$_REQUEST["updata"];
  $upsql="UPDATE question_data SET answered='$answered', ansstr='$updata', timespnt='$timetaken' WHERE questionid='$questionid'";
  $conn->execute_query($upsql);  
}
?>

<form method="REQUEST" action=<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?> style='margin:auto;text-align:center' id="send" >
<input type="hidden" name="questionid" value="<?php echo $questionid ?>" />
<input type="hidden" name="submitted" value="timeout" />
<input type="hidden" name="updata" value="" />
<?php if($answered !='true') 
echo"<input name=\"submitButton\" type=\"submit\" value=\"SUBMIT\">";
?>
</form>


</body>
<script>
window.addEventListener('DOMContentLoaded', () => {
  let tId;
  const form = document.getElementById('send')
  form.addEventListener('submit', (e) => {
    clearTimeout(tId);
    form.querySelector('[name=submitted]').value = 'formsubmit'; // user pressed SUBMIT
    form.querySelector('[name=updata]').value =userchoice.toString();
});
  tId = setTimeout(() => form.submit(),30*60*1000); // submit in 30 minutes
});

var userchoice=['a','b','c'];
//userchoice be the answers that the user has choosen

<?php
if($answered=='false')
echo 'window.onload = CreateTimer("timer",'. $time.');';
else echo 'document.write("Submission Completed");';
?>
</script>

</body>
</html>

But I have something more to know. Is there any way to check if my cookies for storing the time spent are okay? Second, why does the value of php variable $answered is set to "true" though it is supposed to be "false" at the first comment after the body tag?


Solution

  • Please have a look at this version which uses POST and gets rid of the cookies

    The code is not tested and I assume the answers are mad by adding the class "answer" to a clicked div

    window.addEventListener('DOMContentLoaded', () => {
      let tId; // placeholder
      const form = document.getElementById('send')
      form.addEventListener('submit', (e) => {
        clearTimeout(tId); // stop the timeout
        form.querySelector('[name=submitted]').value = 'formsubmit'; // user pressed SUBMIT
        form.querySelector('[name=updata]').value = Array.from(document.querySelectorAll('div.answer')).map(answer => answer.textContent.trim()); // all divs with class = answer.
      });
      tId = setTimeout(() => form.submit(),30*60*1000); // submit in 30 minutes
    });
    
    <?php 
    if (isset($_POST["submitButton"]) || isset($_POST["submitted"]))
      $answered="true";
      $updata = $_POST["updata"]) 
      $upsql="UPDATE question_data SET answered='$answered', ansstr='$updata', timespnt='$timetaken' WHERE questionid='$questionid'";
      $conn->execute_query($upsql);
    ?>
    <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" style="margin:auto;text-align:center" id="send" >
    <input type="hidden" name="questionid" value="<?php echo $questionid ?>" />
    <input type="hidden" name="submitted" value="timeout" />
    <input type="hidden" name="updata" value="" />
    <?php if($answered !='true') {
    <input name="submitButton" type="submit" value="SUBMIT">
    <?php } ?>
    </form>