skip to Main Content

I created a new add to cart button for a custom template, it adds the product to the cart alright, but I have to refresh the page before it appears to my cart drawer. I used a script from the cart.js file and calling this function after adding the cart, but nothing happens.

Here’s the updateCart function:

onCartUpdate() {
    if (this.tagName === 'CART-DRAWER-ITEMS') {
      fetch(`?section_id=cart-drawer`).then((response) => response.text()).then((responseText) => {
        const html = new DOMParser().parseFromString(responseText, 'text/html');
        const selectors = ['cart-drawer-items', '.cart-drawer__footer'];
        for (const selector of selectors) {
          const targetElement = document.querySelector(selector);
          const sourceElement = html.querySelector(selector);
          if (targetElement && sourceElement) {
            targetElement.replaceWith(sourceElement);
          }
        }
      }).catch((e) => {
        console.error(e);
      });
    } else {
      fetch(`${
        routes.cart_url
      }?section_id=main-cart-items`).then((response) => response.text()).then((responseText) => {
        const html = new DOMParser().parseFromString(responseText, 'text/html');
        const sourceQty = html.querySelector('cart-items');
        this.innerHTML = sourceQty.innerHTML;
      }).catch((e) => {
        console.error(e);
      });
    }
  }

I also tried logging the response.text(); but the result is something like this:

<div id="shopify-section-main-cart-items" class="shopify-section">
<cart-items class="gradient color-scheme-1 isolate section-main-cart-items-padding">
  <div class="page-width">
    <div class="title-wrapper-with-link">
      <h1 class="title title--primary">Dein Warenkorb</h1>
      <a href="/collections/all" class="underlined-link">Weiter shoppen</a>
    </div>
      <div class="cart__warnings">
      <h1 class="cart__empty-text">Dein Warenkorb ist leer</h1>
      <a href="/collections/all" class="button">
        Weiter shoppen
      </a></div>

    <form action="/cart" class="cart__contents critical-hidden" method="post" id="cart">
      <div class="cart__items" id="main-cart-items" data-id="main-cart-items">
        <div class="js-contents"><table class="cart-items">
              <caption class="visually-hidden">
                Dein Warenkorb
              </caption>
              <thead>
                <tr>
                  <th class="caption-with-letter-spacing" colspan="2" scope="col">
                    Produkt
                  </th>
                  <th class="medium-hide large-up-hide right caption-with-letter-spacing" colspan="1" scope="col">
                    Gesamtsumme
                  </th>
                  <th
                    class="cart-items__heading--wide cart-items__heading--quantity small-hide caption-with-letter-spacing"
                    colspan="1"
                    scope="col"
                  >
                    Anzahl
                  </th>
                  <th class="small-hide right caption-with-letter-spacing" colspan="1" scope="col">
                    Gesamtsumme
                  </th>
                </tr>
              </thead>.....

2

Answers


  1. You need to append the new item directly in DOM after the succesfull fetch:

    fetch(`?section_id=cart-drawer`).then((response) => response.text()).then((responseText) => {
            const html = new DOMParser().parseFromString(responseText, 'text/html');
            const selectors = ['cart-drawer-items', '.cart-drawer__footer'];
            for (const selector of selectors) {
              const targetElement = document.querySelector(selector);
              const sourceElement = html.querySelector(selector);
              if (targetElement && sourceElement) {
                targetElement.replaceWith(sourceElement);
              }
            }
    
           if(response.ok) {
            var item = `<div><p>${item.name}</p><p>${item.price}</p></div>`
            $('.cart').append(item)
           }
    
          }).catch((e) => {
            console.error(e);
          });
    
    Login or Signup to reply.
  2. // Refresh the cart drawer to reflect changes            
    //document.dispatchEvent(new CustomEvent('cart:build'));
    
    $.getJSON('/cart.js').then(cart=>{
      cartObj = cart;
      document.dispatchEvent(new CustomEvent('cart:updated', {
        detail: {
          cart: cartObj
        }
      }));
      document.dispatchEvent(new CustomEvent('cart:build'));
    });
    
     $.ajax({
      url: window.location.href,
      method: "GET",
      dataType: "html",
      success: function(htmlContent) {
         let doc = new DOMParser().parseFromString(htmlContent, "text/html");
         let cartDrawerElement = doc.querySelector("#CartDrawer .drawer__contents .cart_items_edit_part");
         console.log(cartDrawerElement);
         cartDrawerElement && ($("#CartDrawer .drawer__contents .cart_items_edit_part").replaceWith(cartDrawerElement.outerHTML))
         // $('.m-cart-drawer--inner').removeClass('al-loading-bar loading al-loading-overlay overlay-show');
         // $("body").addClass("overflow-hidden"), $("cart-drawer.drawer").removeClass("is-empty"), $("cart-drawer.drawer").addClass("active")), sellingDataAddInCard()
      },
      error: function(error) {
         console.error("Error fetching and modifying HTML:", error)
      }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search