Shopify Custom AJAX Add to Cart
Enhancing the add-to-cart experience with AJAX improves user engagement by preventing unnecessary page reloads. Below is a step-by-step guide on implementing a custom AJAX add-to-cart function in Shopify.
1. Create an Add to Cart Button
<button id="custom-add-to-cart" data-product-id="123456789">Add to Cart</button> <div id="cart-response"></div>
Replace 123456789 with the actual product variant ID.
2. Write the AJAX Script
document.getElementById('custom-add-to-cart').addEventListener('click', function() {
let productId = this.getAttribute('data-product-id');
fetch('/cart/add.js', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
id: productId,
quantity: 1
})
})
.then(response => response.json())
.then(data => {
document.getElementById('cart-response').innerHTML = 'Item added to cart!';
})
.catch(error => {
console.error('Error:', error);
document.getElementById('cart-response').innerHTML = 'Failed to add item.';
});
});
3. Test Your Implementation
- Ensure your Shopify store is in development mode.
- Click the “Add to Cart” button and verify that the item is added without a page reload.
- Customize the response messages and styles to match your store design.
Â