Reformation Theme AJAX call to update Cart UI

Reformation Theme AJAX call to update Cart UI

Souhailmad14
Shopify Partner
1 0 0

I am implementing a side pannel to sell a customized products. Those products have an add to cart button that unexpectedly follows a different structure to add to cart. Normally all the Product Forms & Add to Cart buttons open the ajax cart updated with the data. This lead me to implement customized script of JS to manage the whole behavior, close the Product Drawer, Open Ajax Cart after adding the cart. The only problem when I fetch in the console log the cart items after clicking on the Add to Cart button it does show the the product is added with Cart Items. However the Cart UI is not updated unless I change the quantity of an exesting item in the cart Item. I would like to know what is the call I need to do to call the update of the UI (that surely change quantity, other add to cart buttons use). 

Here is my script: 

<script>
      if (window.location.href.includes('collection')) {
        document.addEventListener('DOMContentLoaded', function () {
          // Set up event listeners for all quick view buttons
          const quickViewButtons = document.querySelectorAll('quick-view.product-card--add-to-cart-button');
          quickViewButtons.forEach(function (button) {
            button.addEventListener('click', function () {
              console.log('Quick view button clicked. Setting up Mutation Observer.');
              setupFormObserver();
              openProductDrawer(); // Open the Product Drawer
            });
          });

          // Event listener for 'cart:item-added' to open AJAX cart when a product is added
          document.addEventListener('cart:item-added', function (evt) {
            console.log('Cart item added:', evt.detail.product);
            openAjaxCart();
          });
        });

        // Setup Mutation Observer for dynamically loaded content
        function setupFormObserver() {
          const observer = new MutationObserver(function (mutations, observer) {
            for (let mutation of mutations) {
              if (mutation.type === 'childList') {
                const addToCartForm = document.querySelector('.product-form');
                if (addToCartForm) {
                  console.log('Product form loaded. Adding submit event listener.');
                  addToCartForm.addEventListener('submit', handleFormSubmit);
                  observer.disconnect(); // Stop observing once the form is found
                }
              }
            }
          });

          const config = { childList: true, subtree: true };
          const targetNode = document.getElementById('Product-Drawer');
          if (targetNode) {
            observer.observe(targetNode, config);
          } else {
            console.log('Product Drawer not found.');
          }
        }

        // Handle form submission
        function handleFormSubmit(event) {
          event.preventDefault();
          console.log('Form submit event triggered.');

          const formData = new FormData(event.target);
          fetch('/cart/add.js', {
            method: 'POST',
            body: formData,
          })
            .then((response) => response.json())
            .then((data) => {
              console.log('Product added to cart:', data);
              // Emit a custom event to indicate that the cart item has been added
              document.dispatchEvent(new CustomEvent('cart:item-added', { detail: { product: data } }));

              // Now, update the AJAX cart drawer here or in the event listener for 'cart:item-added'
              updateAjaxCart();
              // Now I will do a get to show the itens from cart
              setTimeout(function () {
                jQuery.getJSON('/cart.js', function (cart) {
                  let cartData = cart.items;
                  document.dispatchEvent(new CustomEvent('cart:build', { bubbles: true }));
                  document.dispatchEvent(
                    new CustomEvent('cart:refresh', {
                      bubbles: true,
                      detail: cartData,
                    })
                  );
                });
              }, 400);
              console.log('AJAX cart updated. calld from handleFormSubmit');
            })
            .catch((error) => console.error('Error:', error));
        }

        function updateAjaxCart() {
          // Fetch the latest cart data
          console.log('AJAX cart updated. calld from updateAjaxCart');
          jQuery.getJSON('/cart.js', function (cart) {
            let cartData = cart.items;
          });
        }

        // Function to open Product Drawer
        function openProductDrawer() {
          console.log('Opening Product Drawer.');
          const productDrawer = document.getElementById('Product-Drawer');
          if (productDrawer) {
            productDrawer.style.display = 'block';
          } else {
            console.log('Product Drawer not found.');
          }
        }

        // Open AJAX cart and close Product Drawer if open
        function openAjaxCart() {
          console.log('Opening AJAX cart and closing Product Drawer if open.');

          // Close the Product Drawer
          const productDrawer = document.getElementById('Product-Drawer');
          if (productDrawer) {
            productDrawer.style.display = 'none';
            console.log('Product Drawer closed.');
          } else {
            console.log('Product Drawer not found.');
          }

          // Open the AJAX cart
          const ajaxCart = document.getElementById('Cart-Drawer');
          if (ajaxCart) {
            ajaxCart.classList.add('active');
           
           
            console.log('AJAX cart opened.');
          } else {
            console.log('AJAX cart not found.');
          }
        }
      }
    </script>
Replies 0 (0)