How to Implement Shopify AJAX API: Remove Product from Cart

Solution: Remove a Product from the Cart Using Shopify AJAX API

To remove an item from the Shopify cart using AJAX, you can use the /cart/change.js endpoint. Here’s how:

1. Create a Button for Removing a Product

Add this button inside your cart page (cart.liquid or cart-template.liquid):

<button class="remove-from-cart" data-line="{{ forloop.index }}">
    Remove
</button>

2. JavaScript to Handle Removal via AJAX

Add this script inside your theme’s theme.js or directly in cart.liquid within a <script> tag

document.addEventListener("DOMContentLoaded", function () {
    document.querySelectorAll(".remove-from-cart").forEach((button) => {
        button.addEventListener("click", function () {
            let lineItem = this.getAttribute("data-line");

            fetch("/cart/change.js", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({
                    line: lineItem,
                    quantity: 0,
                }),
            })
            .then(response => response.json())
            .then(data => {
                console.log("Product removed:", data);
                window.location.reload(); // Reload to reflect changes
            })
            .catch(error => console.error("Error:", error));
        });
    });
});

3. Explanation of Code

  • The data-line attribute in the button gets the line item index.
  • When clicked, the script sends a POST request to /cart/change.js with the line number and quantity: 0.
  • After the item is removed, the page reloads to reflect changes.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to Top