everyone! I have been working on a project in JavaScript, usually sending requests to the server using ajax. I want to display a confirmation message and allow the user to press the continue button to continue with the request. When I execute the first click which displays the confirmation dialog, the script runs correctly once. However, when I try clicking on the button again, the script executes twice and keeps incrementing the number of times I click the submit button, it only runs correctly when I refresh the page. Actually, the first click is on a click function that I call on every different result returned from the PHP script and I need the id to send a request against it. I am looking for a way in which I will be able to clear the script execution and let it start over each time I click the submit button. Here is the sample:
...
function removePerson(id) {
$("#confirmDialog").show(function(){
$("#confirm").click(function(){
$.post('server/process.php'{id:id});
});
}
Please, I really need your help with this.
The problem is that you are attaching a new event handler to the confirm button on each call to removePerson.
You can use .off("click") to remove the previous event handler before registering a new one. Something like this should work:
function removePerson(id) {
$("#confirmDialog").show();
$("#confirm").off("click").on("click", function() {
$.post("server/process.php", { id: id });
// just for the demo
console.log(id);
$("#confirmDialog").hide();
});
}
#confirmDialog {
display: none;
padding: 20px;
background: #eee;
margin-bottom: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="confirmDialog">
Remove person? <button id="confirm">confirm</button>
</div>
<button onclick="removePerson(1)">remove ID 1</button>
<button onclick="removePerson(2)">remove ID 2</button>
<button onclick="removePerson(3)">remove ID 3</button>