How to implement add to cart button for each product variant + drawer cart problem

How to implement add to cart button for each product variant + drawer cart problem

Hendrik99
Tourist
6 0 3

hey, i am currently trying to figure out how to implement a certain feature to my product page.

 

I got a product and 3 variants - i want 3 simple, seperate Buy buttons for each variant. If you click on the buy button the drawer cart shall open and the variant should directly be added. So far so good. I got the inspiration from the following store: Link: https://www.stonesthrow.com/store/donuts/

 

I first looked for an app or theme that could do that, but i didnt find any. Then i started coding it together with chatgpt. But now i am really stuck and i need some expertise.

 

So i managed to implement a button for each variant with the variant ids, and also i managed through javascript and the ajax API that if i click on the button the variant is added to the cart. BUT i got problems with the drawer cart. - The cart opens but is empty everytime. If i refresh the page manually the item has actually been added to the cart. I tried a lot but i am currently clueless on how to proceed any further.

If anyone has good input i would be very glad, maybe i ran in the wrong direction. i am no expert, just trying to dig myself into problems and solve them.

Here is the code i got so far:

 

<form class="buy-now-form" data-variant-id="496136360047">
  <button type="button" class="btn">Add to Cart</button>
</form>
<script>
document.addEventListener('DOMContentLoaded', function() {
  const buyNowForms = document.querySelectorAll('.buy-now-form');

  buyNowForms.forEach(function(form) {
    form.addEventListener('click', function(event) {
      event.preventDefault();
      const variantId = form.getAttribute('data-variant-id');

      // Add the product to the cart using Shopify's AJAX API
      fetch('/cart/add.js', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-Requested-With': 'XMLHttpRequest',
        },
        body: JSON.stringify({
          id: variantId,
          quantity: 1,
        }),
      })
      .then(response => response.json())
      .then(data => {
        if (data.status && data.status === 422) {
          // Handle the case where the product can't be added
          console.error('Error adding product to cart:', data.message);
        } else {
          console.log('Item added to cart:', data);

          // Open the cart drawer after adding the item
          const cartDrawer = document.querySelector('cart-drawer');
          if (cartDrawer) {
            cartDrawer.classList.add('active');
            console.log('Cart drawer opened');
          }

          // Optionally, update the cart content dynamically here if needed
        }
      })
      .catch(error => {
        console.error('Error adding item to cart:', error);
      });
    });
  });
});
</script>

 

Replies 0 (0)