Consider this scenario:
form.html
has a link tosend_email.php
.- A user clicks the link twice very quickly.
- The server receives two requests for
send_email.php
and processes them both. send_email.php
sent two emails, but only one should have been sent.
How can we use jQuery to disable the link after the first page request has been made by the browser?
I have built you an elegant MWE. This webpage links to itself and increments a counter with every page request. If you quickly double-click the link (before the current DOM is destroyed to load the page request), it will make two page requests, and you'll see the counter increment by two. Your task is to write jQuery that will allow the first page request to process as usual, but block any subsequent clicks from creating additional page requests.
Many other people ask questions that seem similar but are actually entirely different use cases. Often they want this:
- Display a link or a button on a webpage
- Always block its default event (making a page request or submitting a form)
- Run some arbitrary Javascript exactly once
- Subsequently disable the link or button Here are solutions to this different question.
Notice how my use case is different. I have no Javascript to run. I do want the link or button to work as usual! I want it to work exactly once! All I want is to prevent a user from creating a bunch of page requests by mashing a link or a button. I want to allow the normal link or button function, but only once!
I should be able to drop some jQuery into this PHP script and accomplish exactly what the page describes as the expected behavior.
<?php
sleep(1);
session_name('have-a-cookie');
session_start(['cookie_lifetime' => 3600]);
$_SESSION['counter'] = isset($_SESSION['counter']) ? $_SESSION['counter']+1 : 0;
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<link rel="stylesheet" href="bootstrap.min.css" type="text/css" />
<script src="jquery-3.6.1.min.js"></script>
<script src="bootstrap.bundle.min.js"></script>
<script>
// this does not work
// https://stackoverflow.com/questions/41693832/disable-a-link-after-click-using-jquery
$('.btn').on('click', function(e) {
$(this).prop('disabled',true);
});
</script>
</head>
<body>
<div class="m-3 card text-dark bg-light" style="max-width: 20em;">
<div class="card-body">
<h2>Count: <?php echo $_SESSION['counter']; ?></h2>
<p>The goal is to prevent multiple requests.</p>
<p>Double-clicking the button should make <b>one</b> request and increment the counter by one.</p>
<p><a class="btn btn-primary" href="mwe.php">Count!</a></p>
<p class="mb-0"><a href="mwe.php.txt">Source code</a></p>
</div>
</div>
</body>
</html>