Information



Tags



Share

How to prevent form resubmission when the page is refreshed in PHP

Advertisement:


read_later

Read Later

Keywords



Keywords



read_later

Read Later

Information

Tags

Share





Advertisement

Advertisement



Definition

For my latest web project, I needed to send form information to the page itself without redirecting to any other page to be processed. However, I did not want to resubmit form information after success as the page refreshed. And, I was struggling about finding a way to prevent form resubmission in PHP for my web application which sends form information to the user database via AJAX automatically without using the action attribute. But, in the end, I come up with a solution for my web project by implementing a little bit of JavaScript on PHP as depicted on the code below.

In my solution, first of all, detect each form input is received and saved by the database properly. If it is a successful attempt, then execute the success function to refresh the page without resubmitting the form by printing a script in PHP as you can inspect below.

Code

After executing the code if the response is successful, print the line below as a function named success to refresh the page without resubmitting the form. In that case, the user cannot either resubmit the form inputs or re-run the code with previous variables.

<script> window.location = window.location.href; </script>

Be aware that this syntax is for preventing resubmission while using the POST method or implementing AJAX to send information as well.



<?php

function success(){
echo '<script>window.location = window.location.href;</script>';
}

if(isset($_GET['test'])){
if(!empty($_GET['test'])){
.
.
.
.
.
.
success();

}

}

?>