I am trying to disable a button if a condition met using ajax . But it is not working .
function changeQuantity(cartId, productId, count) {
$.ajax({
url: '/change-product-quantity',
data: {
cart: cartId,
product: productId,
count: count
},
method: 'post',
beforeSend: function() {
// disable your button here
if (count <= 1) {
("#btn").prop("disabled", true);
} else {
("#btn").prop("disabled", false)
}
},
success: (response) => {
alert(response)
}
})
}
2
Answers
The problem with your code is that the beforeSend event handler is called before the AJAX request is sent, but the disable() method of the button element only takes effect after the request is sent.
To fix this, you need to move the disable() method call to the success event handler. This way, the button will be disabled after the request is sent and the response is received.
Here is the code:
Your code is missing the $ selector before
("#btn")
. This is necessary for selecting the button with jQuery. Corrected code: