skip to Main Content

I am using add to cart with custom ajax code and its working fine, problem is I need to open cart drawer on success function by using timber.RightDrawer.open();
For now I am using “js-drawer-open-right” class in form but its open drawer same time when click on add to cart button. I need to open drawer on success of add to cart.

My Ajax code is:

                function addItem(button) {
                var postData = $(button).closest('.add-to-cart').serialize();
                  $.ajax({
                    type: 'POST',
                    url: '/cart/add.js',
                    dataType: 'json',
                    data: postData,
                    success: addToCartOk,
                    error: addToCartFail
                  });
                }
                function addToCartOk(product) {
                //Want to open drawer here on success
                  timber.RightDrawer.open();
                }
                function addToCartFail(obj, status) {
                }

My form is:

Here you can check Add to Cart https://soft-theme.myshopify.com/collections/all

2

Answers


  1. Chosen as BEST ANSWER

    I have find out different and very easy solution for this as compare to timber.RightDrawer.open();

    I have clicked "js-drawer-open-right" with jQuery in success function and removed that class from form which I have placed before.

    The success function now is:

             function addToCartOk(product) {
                //drawer open here by click on that class on success
                  jQuery('.js-drawer-open-right').click();
                }
    

    Its worked perfectly fine.


  2. @barjinder solution but cleaner:

    $(document).on("click", ".add-to-cart-button", function(event) {
        event.preventDefault();
        var form = $(this).closest('form');
        jQuery.ajax({
            type: 'POST',
            url: '/cart/add.js',
            data: form.serialize(),
            dataType: 'json',
            success: function(cart) {
                jQuery('.js-drawer-open-right').click();
            },
            error: function(XMLHttpRequest, textStatus) {
                alert("An error occurred: can't reach server");
            },
        });
    });
    

    You can use the below form

    <form action="/cart/add" method="POST">
        <input type="hidden" name="quantity" value="1">
        <input type="hidden" name="id" value="{{ product.variants.first.id }}">
        <button type="submit" class="add-to-cart-button">
            Add to cart
        </button>
    </form>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search