The history.replaceState method prevents form resubmission by replacing the current page state in the browser's history. This approach is straightforward and does not affect the form submission process.
Example: Preventing Resubmission with Plain JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Prevent Form Resubmission</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 your project already uses jQuery, the same functionality can be implemented inside the $(document).ready function.
Example: Preventing Resubmission with jQuery
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Prevent Form Resubmission</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 eliminates the need for a page reload, which inherently avoids the resubmission problem. It also provides a smoother user experience.
Example: Preventing Resubmission with AJAX and jQuery
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Prevent Form Resubmission</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() {
// Handle form submission with AJAX
$("#exampleForm").on("submit", function(event) {
event.preventDefault(); // Prevent the default form submission
$.ajax({
url: "your-action-url", // Replace with your backend URL
type: "POST",
data: $(this).serialize(), // Serialize form data
success: function(response) {
alert("Form submitted successfully!");
},
error: function(xhr, status, error) {
console.error("Error during form submission:", error);
}
});
});
// Prevent resubmission on page refresh
if (window.history.replaceState) {
window.history.replaceState(null, null, window.location.href);
}
});
</script>
</body>
</html>