Automatic addition and removal of products in Shopify cart

105 Views Asked by At

I am working on a Shopify store where I have a specific requirement for bundling products. When a "Leather Bag" with variant options "Black" and "Medium" is added to the cart, I want to automatically add a "Soft Winter Jacket" to the cart for an additional price of $0.01. Additionally, if the "Leather Bag (Black, Medium)" is removed from the cart, I want the "Soft Winter Jacket" to be automatically removed as well.

Here's the current implementation I have:

<script>
  $('#bundleProduct').on('click', function () {
    // Make an AJAX request to add Leather Bag to the cart
    $.ajax({
        type: 'POST',
        url: '/cart/add.js',
        data: {
            quantity: 1,
            id: 47367576682811,
        },
        dataType: 'json',
        success: function () {
            // After adding Leather Bag to the cart, fetch the cart
            $.ajax({
                type: 'GET',
                url: '/cart.js',
                dataType: 'json',
                success: function (cart) {
                    // Check if Leather Bag is in the cart
                    var leatherBagInCart = cart.items.some(function (item) {
                        return item.variant_id === 47367576682811;
                    });
  
                    // If Leather Bag is in the cart, add Soft Winter Jacket
                    if (leatherBagInCart) {
                        // Make an AJAX request to add Soft Winter Jacket to the cart
                        $.ajax({
                            type: 'POST',
                            url: '/cart/add.js',
                            data: {
                                quantity: 1,
                                id: 47352963072315,
                            },
                            dataType: 'json',
                            success: function () {
                                // Redirect to the cart page or perform other actions
                                console.log('Soft Winter Jacket added to the cart');
                            }
                        });
                    }
                }
            });
        }
    });
  });
</script>

I am facing an issue where the removal of the "Leather Bag" is not automatically removing the "Soft Winter Jacket" from the cart. I've tried making an AJAX request to update the cart when the "remove-item" button is clicked, but it doesn't seem to work as expected.

Can someone please review my code and provide guidance on how I can ensure that the "Soft Winter Jacket" is automatically removed when the "Leather Bag" is removed from the cart?

Thank you in advance for your help.

0

There are 0 best solutions below