How to add and remove the item from the cart on the product page using AJAX

In the 13th article of the #4weeksOfShopifyDev challenge, I'll be talking about how to add and remove the item from the cart on the product page using AJAX.

Let's do it!

  • First, We need to find the add to cart button and get their class name
  • Paste this code in the product template code
<script>
let cartBtn = document.querySelector("YOUR CART BUTTON CLASS NAME")
const form =  document.getElementById("YOUR FORM ID")
form.addEventListener("submit", (e)=>{
e.preventDefault()
addItem()
function addItem() {
$.ajax({
type: 'POST',
url: '/cart/add.js',
dataType: 'json',
data: $('#'+"YOUR FORM ID").serialize()
})
.then(data => {
cartBtn.textContent = "Remove from cart"
cartBtn.setAttribute("data-variant-id", data.variant_id);
})
      }
</script>

In this code snippet, we have added to cart button and add to cart form.

  • We can add an event listener to handle add to cart form submit event and prevent adding product to cart and redirect to the cart page.
  • We have addItem function, it will handle get form data, add the item to the cart, change add to cart text and add the variant id of the product (we'll use in remove item)
function removeItem() {
  let variantId = cartBtn.getAttribute("data-variant-id");
  $.ajax({
    type: "POST",
    url: "/cart/change.js",
    dataType: "json",
    data: {
      id: parseFloat(variantId),
      quantity: 0,
    },
  }).then((data) => {
    cartBtn.textContent = "Add to cart";
    cartBtn.removeAttribute("data-variant-id");
  });
}
  • In this code snippet, we'll remove the same product from the cart.
  • First, we need to get the variant id of the product we want to remove which we set before in addItem function
  • Then, we make an API call to remove the item from the cart and remove the variant id attribute from the cart button

Final code:

<script>
 let cartBtn = document.querySelector("YOUR CART BUTTON CLASS NAME")
const form =  document.getElementById("YOUR FORM ID")
 form.addEventListener("submit", (e)=>{
  e.preventDefault()
  if(cartBtn.getAttribute("data-variant-id")) {
  removeItem()
  }
    else {
      addItem()
    }
 })
 function removeItem() {
   let variantId =  cartBtn.getAttribute("data-variant-id")
   $.ajax({
      type: 'POST',
      url: '/cart/change.js',
      dataType: 'json',
     data: {
  'id': parseFloat(variantId),
  'quantity': 0
}
   })
   .then(data => {
    cartBtn.textContent = "Add to cart"
    cartBtn.removeAttribute("data-variant-id");
})
  }
  function addItem() {
   $.ajax({
      type: 'POST',
      url: '/cart/add.js',
      dataType: 'json',
      data: $('#'+"YOUR FORM ID").serialize()
   })
   .then(data => {
    cartBtn.textContent = "Remove from cart"
    cartBtn.setAttribute("data-variant-id", data.variant_id);
})
          }
</script>
Subscribe below to get notified of new posts.

Related Posts

Convert your Shopify store to PWA for better performances (conversion)

On the 16th of the #4WeeksOfShopifyDev challenge, I’ll be talking Why you should convert your Shopify store to PWA for better performances?

What benefits of being a Shopify partner and make money using it?

On the 15th of the #4WeeksOfShopifyDev challenge, I’ll be talking about what benefits of being a Shopify partner?

Why developers should invest in learning the Shopify App or Theme development?

On the 14th of the #4WeeksOfShopifyDev challenge, I’ll be talking about why developers should invest in learning and becoming a Shopify developer.

Let's Build Something Together

Feel free to reach out if you're looking for a developer, have a question, or just want to connect.

Email:contact@iliashaddad.com

© Ilias Haddad 2021. All rights reserved.

Made with ❤️ in Morocco 🇲🇦