Shopify Custom AJAX Add to Cart

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

  1. Ensure your Shopify store is in development mode.
  2. Click the “Add to Cart” button and verify that the item is added without a page reload.
  3. Customize the response messages and styles to match your store design.

 

Leave a Reply

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

Scroll to Top