skip to Main Content

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


  1. 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:

    function changeQuantity(cartId, productId, count) {
      $.ajax({
        url: '/change-product-quantity',
        data: { cart: cartId, product: productId, count: count },
        method: 'post',
        success: (response) => {
          alert(response);
          // disable your button here
          if (count <= 1) {
            $("#btn").prop("disabled", true);
          } else {
            $("#btn").prop("disabled", false);
          }
        }
      });
    }
    
    Login or Signup to reply.
  2. Your code is missing the $ selector before ("#btn"). This is necessary for selecting the button with jQuery. Corrected code:

    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)
            }
        })
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search