I have two buttons that add or substract a quantity of a product and update the price etc on a digital receipt using ajax. The problem is when a user spams the button the quantity does not align with the quantity in the input box.
For example if I click really fast, the input box can have a quantity value of 10 and the receipt will say 8.
How can I prevent that?
I was thinking to only make the buttons trigger the function once the ajax call is finished.
This is my code:
$(".formatenkeuze .plusmin").on("click", function(e, anchorObject, stepNumber, stepDirection, stepPosition) {
if($('#aantalinput').val() > 0) {
$('.formateninput').removeClass('alertmessage');
$('.controlemelding').hide();
var form_data = $("#formsid form").serialize();
$.ajax({
type:'post',
url:"catalog/calcdiv.php",
data:({form_data: form_data}),
success:function(data){
var obj = JSON.parse(data);
$( "#ajaxresult" ).empty().append( obj[0].productinfo );
$('#prijsonder').empty().append($('#prijs').html());
}
});
} else{
$('.formateninput').addClass('alertmessage');
$('.controlemelding').css('display','flex');
}
});
Maybe set a variable to false
on click and only set it to true
when an ajax call is complete and only make the function trigger when the variable is set to true
?
4
Answers
Assuming the button is a
<input type="button">
or<button>
element then you can simply disable it before sending the AJAX request and enable it again when the call completes. Try this:Note: the timeout represents your ajax call
You can hide the button after clicking and display it again once the ajax success handler executes:
Disabling the button when the button is pressed and enabling the button again after the ajax call has completed will prevent users from spam clicking your button.
You can disable/enable your button with jQuery like this:
Just simply disable it the moment you click it.