How to Prevent Duplicate Form Submissions with JavaScript and PHP
Stop double clicks, repeated form submissions, and duplicate database records with a practical JavaScript and PHP solution. Learn why disabling a button isn't enough and how to make form processing reliable.
A visitor fills out a contact form and clicks Send. Nothing seems to happen immediately, so they click again.
A few seconds later, your website receives two identical messages.
On an ecommerce site, the same problem might create duplicate requests, subscriptions, or database records. Even when the server is working correctly, an impatient visitor, a slow connection, or an accidental retry can trigger repeated submissions.
The common solution is to disable the Submit button after the first click.
That helps, but it doesn't completely solve the problem.
A reliable implementation needs two layers: JavaScript to improve the user experience and PHP to ensure that repeated requests don't create duplicate operations.
Let's build both, step by step.
1. Why do forms get submitted more than once?
Duplicate submissions have several possible causes:
- A visitor double-clicks the Submit button.
- The server takes several seconds to respond.
- The visitor refreshes the page after a POST request.
- The browser or an intermediary retries a request.
- A JavaScript event handler accidentally sends the request twice.
- Two requests arrive almost simultaneously.
The last case is particularly important.
Even if JavaScript prevents a second click in the browser, it cannot guarantee that the server receives only one request.
A visitor can disable JavaScript, open multiple tabs, or resend an HTTP request.
That's why frontend protection should never be the only defense.
2. Start with a simple HTML form
We'll use a contact request as our example.
<form id="contactForm" action="contact.php" method="post">
<div>
<label for="contactName">Your name</label>
<input type="text" id="contactName" name="name" required>
</div>
<div>
<label for="contactEmail">Your email</label>
<input type="email" id="contactEmail" name="email" required>
</div>
<div>
<label for="contactMessage">Your message</label>
<textarea id="contactMessage" name="message" required></textarea>
</div>
<button type="submit" id="submitButton">Send message</button>
</form>
This is ordinary HTML, compatible with modern browsers.
The browser already provides basic form validation through attributes such as required and type="email".
However, HTML validation doesn't prevent duplicate submissions or replace server-side validation.
3. Prevent repeated clicks with JavaScript
The first improvement is to disable the Submit button when the form is submitted.
const form = document.getElementById('contactForm');
const submitButton = document.getElementById('submitButton');
let isSubmitting = false;
form.addEventListener('submit', (event) => {
if (isSubmitting) {
event.preventDefault();
return;
}
isSubmitting = true;
submitButton.disabled = true;
submitButton.textContent = 'Sending...';
});
The script listens for the form's submit event, rather than the button's click event.
This distinction matters because a form can also be submitted by pressing Enter in an input field.
The submit event is triggered after successful native constraint validation. If required fields are invalid, the event doesn't fire, so the button isn't prematurely disabled.
The isSubmitting variable also blocks another submission attempt during the same page lifecycle.
Why not listen only for clicks?
Consider this code:
submitButton.addEventListener('click', () => {
submitButton.disabled = true;
});
It can cause problems.
The button might become disabled before the browser has completed validation, leaving the visitor unable to correct an invalid form and submit again.
It also doesn't reliably cover every way a form can be submitted.
The form's submit event is the better starting point.
4. Show clear feedback to the visitor
Disabling a button without explanation can make a website feel unresponsive.
Add a visible status message.
<p id="formStatus" role="status" aria-live="polite"></p>
Then update the JavaScript:
const form = document.getElementById('contactForm');
const submitButton = document.getElementById('submitButton');
const formStatus = document.getElementById('formStatus');
let isSubmitting = false;
form.addEventListener('submit', (event) => {
if (isSubmitting) {
event.preventDefault();
return;
}
isSubmitting = true;
submitButton.disabled = true;
submitButton.textContent = 'Sending...';
formStatus.textContent = 'Please wait while we send your message.';
});
The status message tells the visitor that their action was received.
For an AJAX form, the button should be re-enabled if the request fails and the visitor needs to retry.
For a traditional HTML form, the browser normally navigates to the response page.
5. Understand why JavaScript isn't enough

Imagine that two identical POST requests reach the server at almost the same time.
Both requests may pass frontend checks, because they are independent HTTP requests.
A simple PHP script such as this doesn't protect against duplicates:
<?php
// Simplified example: not duplicate-safe.
$stmt = $pdo->prepare(
'INSERT INTO contact_requests (email, message)
VALUES (:email, :message)'
);
$stmt->execute([
'email' => $_POST['email'],
'message' => $_POST['message'],
]);
Each execution creates another database record.
Checking whether the same email and message already exist isn't necessarily a solution either. A visitor might legitimately send the same message twice on different occasions.
What we need is a way to identify one logical submission, regardless of how many times it reaches the server.
This is where a unique submission identifier becomes useful.
6. Generate a unique submission ID in PHP
When displaying the form, generate a random identifier:
<?php
$submissionId = bin2hex(random_bytes(16));
?>
The PHP random_bytes() function generates cryptographically secure random bytes. Converting them with bin2hex() creates a hexadecimal string suitable for an HTML hidden field.
Add the identifier to the form:
<input
type="hidden"
name="submission_id"
value="<?= htmlspecialchars($submissionId, ENT_QUOTES, 'UTF-8') ?>"
>
For example:
submission_id = 8b4c7f2e1d6a903b5e4f8c2a7d1e6b90
The identifier represents one attempt to submit the form.
If the same form is submitted twice, both requests carry the same identifier.
If the visitor opens a new form later, PHP generates a different identifier.
Important: this is a duplicate-prevention identifier, not an authentication token or a CSRF protection mechanism. A production form still needs its usual security controls.
7. Create a MariaDB table that rejects duplicates
The most reliable protection is to enforce uniqueness at the database level.
You can create the table using phpMyAdmin or your hosting provider's database interface, without opening a terminal.
CREATE TABLE contact_requests (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
submission_id CHAR(32) NOT NULL,
name VARCHAR(150) NOT NULL,
email VARCHAR(254) NOT NULL,
message TEXT NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY unique_submission (submission_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
The essential part is:
UNIQUE KEY unique_submission (submission_id)
MariaDB won't allow two rows with the same submission identifier.
Unlike a PHP-only check performed before insertion, a unique database constraint also protects against concurrent requests.
Two requests may arrive simultaneously, but they cannot both successfully insert a row with the same unique key.
8. Handle the submission safely in PHP
Here's the essential server-side processing logic, assuming the database connection is already available as $pdo.
<?php
declare(strict_types=1);
$submissionId = $_POST['submission_id'] ?? '';
$name = trim((string) ($_POST['name'] ?? ''));
$email = trim((string) ($_POST['email'] ?? ''));
$message = trim((string) ($_POST['message'] ?? ''));
if (
!is_string($submissionId)
|| !preg_match('/^[a-f0-9]{32}$/', $submissionId)
|| $name === ''
|| !filter_var($email, FILTER_VALIDATE_EMAIL)
|| $message === ''
) {
http_response_code(422);
exit('Please check the submitted information.');
}
if (mb_strlen($name) > 150 || mb_strlen($email) > 254) {
http_response_code(422);
exit('One or more fields are too long.');
}
try {
$stmt = $pdo->prepare(
'INSERT INTO contact_requests
(submission_id, name, email, message)
VALUES
(:submissionId, :name, :email, :message)'
);
$stmt->execute([
'submissionId' => $submissionId,
'name' => $name,
'email' => $email,
'message' => $message,
]);
echo 'Your message has been received.';
} catch (PDOException $exception) {
$errorInfo = $exception->errorInfo;
$mysqlError = (int) ($errorInfo[1] ?? 0);
if ($mysqlError === 1062) {
// Duplicate key: this submission was already recorded.
echo 'This message has already been received.';
} else {
// Log the actual error privately.
error_log($exception->getMessage());
http_response_code(500);
echo 'An error occurred. Please try again later.';
}
}
This example uses PDO prepared statements to insert the submitted data.
If the database returns MariaDB/MySQL error 1062, the submission identifier already exists.
Instead of creating another record, the script returns an appropriate message.
The database connection should be configured with PDO::ERRMODE_EXCEPTION.
The example focuses on duplicate prevention. A complete public contact form also needs CSRF protection, spam prevention, appropriate input limits, and access controls where applicable.
If the request triggers an external action such as sending an email, inserting the row alone doesn't guarantee exactly-once delivery. A more robust design records a pending job in the database and processes it separately, with its own duplicate-handling rules.
9. Prevent duplicate submissions after a page refresh
Another common problem occurs when visitors refresh a page after submitting a form.
The browser may offer to resend the POST request.

A standard solution is the Post/Redirect/Get pattern, commonly abbreviated as PRG.
The workflow is: POST (submit form), HTTP 303 (redirect), GET (result page). The visitor ends up on a GET page, which can be refreshed without resubmitting the POST.
After processing a valid submission, redirect to a confirmation page:
header('Location: /message-received.php', true, 303);
exit;
The 303 See Other status tells the browser to retrieve the destination using GET.
This prevents the usual POST resubmission prompt when the confirmation page is refreshed.
PRG improves navigation behavior, but it doesn't replace the database unique constraint. A duplicate request could still arrive before the redirect is processed.
10. What about AJAX forms?
Many modern forms submit data using fetch() instead of a normal browser navigation.
In that case, the script should prevent the browser's default submission, send the request, and manage the loading state.
const form = document.getElementById('contactForm');
const button = document.getElementById('submitButton');
const status = document.getElementById('formStatus');
let isSubmitting = false;
form.addEventListener('submit', async (event) => {
event.preventDefault();
if (isSubmitting) {
return;
}
isSubmitting = true;
button.disabled = true;
status.textContent = 'Sending...';
try {
const response = await fetch(form.action, {
method: 'POST',
body: new FormData(form)
});
if (!response.ok) {
throw new Error('Submission failed');
}
status.textContent = 'Your message has been received.';
form.reset();
} catch (error) {
status.textContent =
'The request could not be confirmed. You can retry.';
} finally {
isSubmitting = false;
button.disabled = false;
}
});
This example assumes the PHP endpoint returns an HTTP success status for a successfully processed or already-recorded submission.
For a real application, use a structured JSON response if you need to distinguish successful processing, duplicate requests, and validation errors.
A particularly important detail: do not generate a new submission identifier simply because a network request failed.
The server may have received and processed the original request even if the browser never received its response.
A retry of the same logical operation should reuse the same identifier.
Only generate a new identifier when the visitor starts a genuinely new submission.
11. Test the protection before publishing
You can test the solution using your browser and phpMyAdmin.
| Test | Expected result |
|---|---|
| Double-click Send quickly | One browser submission attempt |
| Press Enter repeatedly | No repeated submission while processing |
| Submit invalid fields | Validation appears; form remains usable |
Send the same submission_id twice |
Only one database row |
| Open a new form and submit it | A new row can be created |
| Refresh the confirmation page | No POST resubmission |
| Simulate a network error | Retry remains possible |
| Submit two requests concurrently | Unique constraint rejects the duplicate |
For the database test, open phpMyAdmin and inspect the contact_requests table.
You can also run:
SELECT
submission_id,
COUNT(*) AS occurrences
FROM contact_requests
GROUP BY submission_id
HAVING COUNT(*) > 1;
With the unique constraint in place, this query should return no rows.
If duplicates still appear in another table or external service, investigate whether that operation is actually protected by the same submission identifier.
12. WordPress and Joomla: do you need custom code?
Not necessarily.
If you use a WordPress form plugin or a Joomla form extension, first inspect its existing features.
Some extensions provide submission locking, duplicate detection, AJAX loading indicators, or spam protection.
Before adding custom JavaScript, verify whether the extension already manages the Submit button and request lifecycle. Otherwise, two competing event handlers may interfere with each other.
For custom WordPress development, use the platform's supported form processing mechanisms and nonce verification.
For Joomla extensions, use the framework's request handling and CSRF token facilities.
The same fundamental principle applies regardless of the CMS: frontend locking improves usability, while server-side duplicate handling protects data integrity.
13. Common mistakes to avoid
| Mistake | Why it's a problem | Better solution |
|---|---|---|
| Disable button on click | Can interfere with validation | Use the form's submit event |
| Rely only on JavaScript | Requests can bypass the browser | Enforce uniqueness server-side |
| Compare message text | Identical messages may be legitimate | Use a submission identifier |
| Check existence before insert | Concurrent requests can pass the check | Use a database unique constraint |
| Generate a new ID on every retry | Same operation may be processed twice | Reuse the original ID |
| Show success before server confirmation | Visitor may believe a failed request succeeded | Wait for the response |
| Use PRG as the only defense | Concurrent POSTs remain possible | Combine PRG with database protection |
| Ignore external side effects | Emails or payments may still duplicate | Protect downstream operations too |
Conclusion: prevent duplicates at both ends
Preventing duplicate form submissions isn't just about disabling a button.
JavaScript helps visitors understand that their request is being processed and prevents accidental repeated interactions.
PHP and MariaDB provide the more important guarantee: the same logical submission cannot create multiple database records when a unique identifier is enforced correctly.
Combine these protections with Post/Redirect/Get for traditional forms, careful retry handling for AJAX requests, and appropriate security checks.
The result is a more reliable experience for visitors and cleaner, more predictable data for your application.