I have the following function which does some checks via ajax and enables/disables an add to cart button:
function formUpdate() {
var data = {
'action': 'my_action_name',
'qty': $( '#qty' ).val(),
};
var request = jQuery.ajax({
url: 'myajax.php',
method: "POST",
data: data,
async: true
});
request.done( function( response ) {
// I disable my add to cart button here
// Some code that takes a while to run to determine if add to cart should be enabled
// I conditionally enable the add to cart here based on the above
}
}
$( '#qty' ).on( 'change', function() {
formUpdate();
});
The request is triggered when #qty (number) field is changed, when a user presses the up/down arrows on the field or uses the up/down keys the ajax request is sent multiple times and because the code in the request.done takes a while if the requests near the end result in a disabled add to cart button there is a brief period where the previous requests keep it enabled until the later requests are done - so a user could add to cart in that brief moment.
I want to eliminate this from occurring, I know I can use async: false, but this stops the user from using up/down arrows/keys until the request is done.
What I'd like to do is keep async: true, but ensure the add to cart remains disabled until all requests are completed - I have tried disabling the add to cart before the ajax request in the formUpdate function but this doesn't appear to work, assumed because of all the ajax requests enabling/disabling the add to cart button.
I am wondering if there is a way I can use the action name I am passing in data for the ajax request, then have a function that disables the add to cart button until all of the ajax requests with that name are finished running.
I have looked around for code for this but most of what I have found is related to ALL ajax requests, not specific ones.
Is this possible or is there another solution?