Update Cart Item Quantity Using Shopify AJAX API

Update Cart Item Quantity Using Shopify AJAX API

Shopify provides the /cart/change.js endpoint, which allows us to update the quantity of an item in the cart dynamically without a page reload.

1. Add Input Field and Update Button in cart.liquid

Modify your cart page to include an input field for quantity and an update button.

<form class="cart-update-form">
    <input type="number" class="cart-quantity" data-line="{{ forloop.index }}" value="{{ item.quantity }}" min="1">
    <button type="button" class="update-cart" data-line="{{ forloop.index }}">Update</button>
</form>

2. JavaScript to Handle Cart Updates via AJAX

Place this script in theme.js or add it in a <script> tag inside cart.liquid.

document.addEventListener("DOMContentLoaded", function () {
    document.querySelectorAll(".update-cart").forEach((button) => {
        button.addEventListener("click", function () {
            let lineItem = this.getAttribute("data-line");
            let newQuantity = document.querySelector(`.cart-quantity[data-line="${lineItem}"]`).value;

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

3. Explanation of the Code

  • The cart-quantity input allows users to enter a new quantity.
  • The update-cart button sends a POST request to /cart/change.js with:
    • line → The line item position in the cart.
    • quantity → The updated quantity entered by the user.
  • After updating the cart, the page reloads to reflect changes.

Leave a Reply

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

Scroll to Top