How to prevent PHP HTML form resubmission when page is refreshed/reload (F5/CTRL+R)?
When a user submits a form, the browser can resend the data if the user refreshes the page. This can lead to duplicate data submissions.
One way to prevent resubmit data is to use the javascript 'history.replaceState' method.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Prevent Form Resubmit</title>
</head>
<body>
<form id="exampleForm" method="post" action="your-action-url">
<input type="text" name="example" required />
<input type="submit" value="Submit" />
</form>
<script>
document.addEventListener("DOMContentLoaded", function() {
if (window.history.replaceState) {
window.history.replaceState(null, null, window.location.href);
}
});
</script>
</body>
</html>
If you're using jQuery, you can perform the same operation inside the '$(document).ready' function to ensure that the DOM is ready before executing 'replaceState'.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Prevent Form Resubmit</title>
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<form id="exampleForm" method="post" action="your-action-url">
<input type="text" name="example" required />
<input type="submit" value="Submit" />
</form>
<script>
$(document).ready(function() {
if (window.history.replaceState) {
window.history.replaceState(null, null, window.location.href);
}
});
</script>
</body>
</html>
Using AJAX for form submission can improve user experience by not requiring a page reload, hence eliminating the need to handle form resubmission.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Prevent Form Resubmit</title>
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<form id="exampleForm" method="post">
<input type="text" name="example" required />
<input type="submit" value="Submit" />
</form>
<script>
$(document).ready(function() {
$("#exampleForm").on("submit", function(event) {
event.preventDefault(); // Prevent default form submission
$.ajax({
url: "your-action-url",
type: "POST",
data: $(this).serialize(),
success: function(response) {
alert("Form submitted successfully");
},
error: function(xhr, status, error) {
console.error("Submission error:", error);
}
});
});
if (window.history.replaceState) {
window.history.replaceState(null, null, window.location.href);
}
});
</script>
</body>
</html>