JAVASCRIPTshopifyintermediate

Shopify AJAX Add to Cart

Add products to cart without page reload using Shopify AJAX API

#shopify#ajax#cart#javascript#add-to-cart
Share this snippet:

Code

javascript
1// Add to cart with AJAX
2function addToCart(variantId, quantity = 1) {
3 const formData = {
4 items: [{
5 id: variantId,
6 quantity: quantity
7 }]
8 };
9
10 fetch('/cart/add.js', {
11 method: 'POST',
12 headers: {
13 'Content-Type': 'application/json',
14 },
15 body: JSON.stringify(formData)
16 })
17 .then(response => {
18 if (!response.ok) {
19 throw new Error('Network response was not ok');
20 }
21 return response.json();
22 })
23 .then(data => {
24 console.log('Success:', data);
25
26 // Update cart count
27 updateCartCount();
28
29 // Show success message
30 showNotification('Product added to cart!');
31
32 // Optional: Open cart drawer
33 openCartDrawer();
34 })
35 .catch((error) => {
36 console.error('Error:', error);
37 showNotification('Failed to add product to cart', 'error');
38 });
39}
40
41// Update cart count
42function updateCartCount() {
43 fetch('/cart.js')
44 .then(response => response.json())
45 .then(cart => {
46 const cartCount = document.querySelector('.cart-count');
47 if (cartCount) {
48 cartCount.textContent = cart.item_count;
49 }
50 });
51}
52
53// Show notification
54function showNotification(message, type = 'success') {
55 const notification = document.createElement('div');
56 notification.className = `notification notification--${type}`;
57 notification.textContent = message;
58 document.body.appendChild(notification);
59
60 setTimeout(() => {
61 notification.remove();
62 }, 3000);
63}
64
65// Example usage with product form
66document.querySelectorAll('form[action="/cart/add"]').forEach(form => {
67 form.addEventListener('submit', function(e) {
68 e.preventDefault();
69
70 const variantId = form.querySelector('[name="id"]').value;
71 const quantity = form.querySelector('[name="quantity"]')?.value || 1;
72
73 addToCart(variantId, parseInt(quantity));
74 });
75});

Shopify AJAX Add to Cart

This snippet allows you to add products to the Shopify cart without a page reload using the AJAX Cart API. It includes error handling and cart drawer update.

// Add to cart with AJAX
function addToCart(variantId, quantity = 1) {
  const formData = {
    items: [{
      id: variantId,
      quantity: quantity
    }]
  };

  fetch('/cart/add.js', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(formData)
  })
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => {
    console.log('Success:', data);

    // Update cart count
    updateCartCount();

    // Show success message
    showNotification('Product added to cart!');

    // Optional: Open cart drawer
    openCartDrawer();
  })
  .catch((error) => {
    console.error('Error:', error);
    showNotification('Failed to add product to cart', 'error');
  });
}

// Update cart count
function updateCartCount() {
  fetch('/cart.js')
    .then(response => response.json())
    .then(cart => {
      const cartCount = document.querySelector('.cart-count');
      if (cartCount) {
        cartCount.textContent = cart.item_count;
      }
    });
}

// Show notification
function showNotification(message, type = 'success') {
  const notification = document.createElement('div');
  notification.className = `notification notification--${type}`;
  notification.textContent = message;
  document.body.appendChild(notification);

  setTimeout(() => {
    notification.remove();
  }, 3000);
}

// Example usage with product form
document.querySelectorAll('form[action="/cart/add"]').forEach(form => {
  form.addEventListener('submit', function(e) {
    e.preventDefault();

    const variantId = form.querySelector('[name="id"]').value;
    const quantity = form.querySelector('[name="quantity"]')?.value || 1;

    addToCart(variantId, parseInt(quantity));
  });
});

Features

  • No Page Reload: Adds products without refreshing the page
  • Error Handling: Catches and displays errors gracefully
  • Cart Count Update: Automatically updates cart counter
  • Notification System: Shows success/error messages
  • Progressive Enhancement: Works with existing forms

Usage with Liquid

Add this to your product form:

<form action="/cart/add" method="post" class="product-form">
  <input type="hidden" name="id" value="{{ product.selected_or_first_available_variant.id }}">

  <input type="number" name="quantity" value="1" min="1">

  <button type="submit" class="btn btn--primary">
    Add to Cart
  </button>
</form>

Styling the Notification

.notification {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 15px 20px;
  border-radius: 4px;
  color: white;
  font-weight: 500;
  z-index: 9999;
  animation: slideIn 0.3s ease;
}

.notification--success {
  background: #10b981;
}

.notification--error {
  background: #ef4444;
}

@keyframes slideIn {
  from {
    transform: translateX(400px);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

Related Snippets