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-lineattribute in the button gets the line item index. - When clicked, the script sends a
POSTrequest to/cart/change.jswith the line number andquantity: 0. - After the item is removed, the page reloads to reflect changes.