How can I create an Ajax add to cart button in a custom section?

KPSLuke
Shopify Partner
6 0 0

SO i have Created a section that renders products, but when i click add to cart it redirects to cart page. I want to create a ajax add to cart button, that when clicked will show the products in the cart and update the cart count total. 

Pretty much dawns quick add for the collections but in my own custom section. 


Thank you in advance.

Section

 

 

 

<div class="product-display" id="product-display">
  <div class="product-display__container">
    <div
      class="product__display"
      id="product__display"
      style="padding-top: {{ section.settings.product_display_padding }}px; padding-bottom: {{ section.settings.product_display_padding }}px;"
    >
      <div class="product-display-collection" id="product-display-collection">
        {% if section.settings.product_display_collection %}
          {% assign product_limit = section.settings.product_display_limit | default: 4 %}
          {% assign collection_handle = section.settings.product_display_collection.handle %}
          {% assign collection = collections[collection_handle] %}
          {% if collection.products.size > 0 %}
            <div class="product-list" id="product-list">
              {% for product in collection.products limit: product_limit %}
                <div class="product-item" id="product-item-{{ forloop.index }}">
                  <a href="{{ product.url }}">
                    <div class="product-image" id="product-image-{{ forloop.index }}">
                      <img src="{{ product.featured_image.src | img_url: 'medium' }}" alt="{{ product.title }}">
                    </div>
                  </a>
                  <div class="product-details" id="product-details-{{ forloop.index }}">
                    <a href="{{ product.url }}">
                      <h3 class="product-title" id="product-title-{{ forloop.index }}">{{ product.title }}</h3>
                    </a>
                    <div class="product__price">
                      <a href="{{ product.url }}">
                        <p class="product-price" id="product-price-{{ forloop.index }}">{{ product.price | money }}</p>
                      </a>
                    </div>
                    <form action="/cart/add" method="post">
                      <input type="hidden" name="id" value="{{ product.variants.first.id }}">
                      <button type="submit" class="add-to-cart-btn">Add to Cart</button>
                    </form>
                  </div>
                </div>
              {% endfor %}
            </div>
          {% else %}
            <p class="no-products-message" id="no-products-message">No products in the selected collection.</p>
          {% endif %}
        {% else %}
          <p class="no-collection-message" id="no-collection-message">No collection selected.</p>
        {% endif %}
      </div>
      <div class="product-display-image-wrapper" id="product-display-image-wrapper">
        <div class="product-display-image" id="product-display-image">
          <div class="product_side-image" id="ProductSideImage">
            {% if section.settings.product_display_image %}
              <a href="{{ section.settings.product_display_image.url }}">
                <img
                  class="image"
                  src="{{ section.settings.product_display_image | img_url: 'medium' }}"
                  alt="Product Display Image"
                >
              </a>
            {% else %}
              <p class="no-image-message" id="no-image-message">No image selected.</p>
            {% endif %}
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

 

 

 

 

Replies 9 (9)

Rishihuptech
Shopify Partner
469 80 86

Hello @KPSLuke , Try adding the below script to your code.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> {% comment %} If you have added the jQuery CDN already do not add {% endcomment %}
<script>
document.addEventListener('DOMContentLoaded', function () {
  const formSubmit = "[action='/cart/add']";
  $(formSubmit).on('submit', function(e) {
    e.preventDefault(); // Prevent the default form submission
    
    var productId = $(this).find('input[name="id"]').val();
    
    $.ajax({
      type: 'POST',
      url: '/cart/add.js',
      data: {
        quantity: 1,
        id: productId
      },
      dataType: 'json',
      success: function(response) {
        var cartMessage = $('<div class="cart-message">Item added to cart</div>').appendTo(formSubmit).fadeIn('fast');
        setTimeout(function() {
          cartMessage.fadeOut('slow', function() {
            $(this).remove();
          });
        }, 3000);

        $.ajax({
          type: 'GET',
          url: '/cart.js',
          dataType: 'json',
          success: function(cart) {
            $('.cart-count-bubble').remove();
            var cartCount = $('#cart-icon-bubble');

            var cartCountBubbleHtml = '<div class="cart-count-bubble"><span aria-hidden="true">' + cart.item_count + '</span><span class="visually-hidden">' + cart.item_count + (cart.item_count === 1 ? ' item' : ' items') +'</span></div>';
            $(cartCountBubbleHtml).appendTo(cartCount);
            
            // $('.cart-count-bubble span[aria-hidden="true"]').text(cart.item_count);
            // $('.cart-count-bubble span.visually-hidden').text(cart.item_count + (cart.item_count === 1 ? ' item' : ' items'));
            
          },
          error: function(XMLHttpRequest, textStatus) {
            console.log('Error getting cart count:', textStatus);
          }
        });
        
      },
      error: function(XMLHttpRequest, textStatus) {
        console.log('Error occurred: ' + textStatus);
      }
    });
  });
});
</script>
If you found this response helpful, please do like and accept the solution. Thanks!
Need support with Customizing your Shopify store?
Feel free to contact me at info@huptechweb.com or Visit our website Huptech Web.
Instant Shortcode Builder: Integrate customizable UI features anywhere in your store - No coding knowledge required
KPSLuke
Shopify Partner
6 0 0

That works perfectly the only thing im trying to get to work next was having the cart ui update when an item is added to cart without redirecting or page refresh. But otherwise your solution has helped me alot.

KPSLuke
Shopify Partner
6 0 0

@Rishihuptech Sorry i forgot to mention your name

Rishihuptech
Shopify Partner
469 80 86

Hello @KPSLuke , You want to show the Cart count on the mini cart icon, Correct?

If you found this response helpful, please do like and accept the solution. Thanks!
Need support with Customizing your Shopify store?
Feel free to contact me at info@huptechweb.com or Visit our website Huptech Web.
Instant Shortcode Builder: Integrate customizable UI features anywhere in your store - No coding knowledge required
KPSLuke
Shopify Partner
6 0 0

@Rishihuptech I want to update the cart count and the cart drawer, without having to refresh the page or be redirected to cart url. Want to update cart contents in real time

 

 

Rishihuptech
Shopify Partner
469 80 86

Okay @KPSLuke , can you please your store URL? I need to check it for the cart drawer functionality.

If you found this response helpful, please do like and accept the solution. Thanks!
Need support with Customizing your Shopify store?
Feel free to contact me at info@huptechweb.com or Visit our website Huptech Web.
Instant Shortcode Builder: Integrate customizable UI features anywhere in your store - No coding knowledge required
KPSLuke
Shopify Partner
6 0 0
KPSLuke
Shopify Partner
6 0 0

@Rishihuptech 

url = https://gadgettimeza.myshopify.com/

password: testpassword

Rishihuptech
Shopify Partner
469 80 86

Hello @KPSLuke , Please replace the below script with the script I provided Yesterday! 

<script>
document.addEventListener('DOMContentLoaded', function () {
function updateCartItemCount() {
  $.ajax({
    type: 'GET',
    url: '/cart.js',
    dataType: 'json',
    success: function(cart) {
    var cartCount = document.getElementById('cart-icon-bubble');
      var cartCountBubbleHtml = '<div class="cart-count-bubble"><span aria-hidden="true">' + cart.item_count + '</span><span class="visually-hidden">' + cart.item_count + (cart.item_count === 1 ? ' item' : ' items') +'</span></div>';
      var cartCountBubbleElement = document.createElement('div');
      cartCountBubbleElement.innerHTML = cartCountBubbleHtml;
      cartCount.appendChild(cartCountBubbleElement);
    },
    error: function(XMLHttpRequest, textStatus) {
      console.log('Error getting cart count:', textStatus);
    }
  });
}
  const addToCart = document.querySelectorAll('.addToCartForm');

  addToCart.forEach(function(atc) {
    atc.addEventListener('click', function(e){
      e.preventDefault(); // Prevent the default form submission

   var productId = this.querySelector('input[name="id"]').value;
    
    $.ajax({
      type: 'POST',
      url: '/cart/add.js',
      data: {
        quantity: 1,
        id: productId
      },
      dataType: 'json',
      success: function(response) {
        var cartMessage = document.createElement('div');
        cartMessage.classList.add('cart-message');
        cartMessage.textContent = 'Item added to cart';
        
        // Append the created div element to the atc element
        atc.appendChild(cartMessage);
        
        // Fade in the cart message
        cartMessage.style.display = 'none'; 
        cartMessage.style.display = 'block';
        cartMessage.style.transition = 'opacity 0.2s';
        setTimeout(function() {
          cartMessage.style.opacity = '0';
          setTimeout(function() {
            atc.removeChild(cartMessage);
          }, 200);
        }, 3000);
        
        updateCartItemCount();

        $.ajax({
          type: 'GET',
          url: window.Shopify.routes.root + "?sections=cart-drawer",
          dataType: 'json',
          success: function(cart) {
           
          const parser = new DOMParser();

          // Parse the HTML string
          const htmlObject = parser.parseFromString(cart['cart-drawer'], 'text/html');
          const cartHtml=htmlObject.querySelector("cart-drawer");
          const maincart=document.querySelector("cart-drawer");
          maincart.innerHTML=cartHtml.innerHTML;
          maincart.classList.add("active");
          maincart.classList.remove('is-empty');
          document.querySelector('body').classList.add('overflow-hidden');
          function attachEventListeners() {
            const closeCartDrawer = document.getElementById('CartDrawer-Overlay');
            if(closeCartDrawer){
              closeCartDrawer.addEventListener('click', function(event) {
                document.querySelector("cart-drawer").classList.remove('active');
                document.querySelector('body').classList.remove('overflow-hidden');
              });
            }
          }
            attachEventListeners()
          },
          error: function(XMLHttpRequest, textStatus) {
            console.log('Error getting cart count:', textStatus);
          }
        });
        
      },
      error: function(XMLHttpRequest, textStatus) {
        console.log('Error occurred: ' + textStatus);
      }
    });
    });
  });
});
</script>

 

Also, please add the "addToCartForm" class to your add-to-cart form.

<form action="/cart/add" method="post" class="addToCartForm">
   <input type="hidden" name="id" value="{{ product.variants.first.id }}">
   <button type="submit" class="add-to-cart-btn">Add to Cart</button>
</form>
If you found this response helpful, please do like and accept the solution. Thanks!
Need support with Customizing your Shopify store?
Feel free to contact me at info@huptechweb.com or Visit our website Huptech Web.
Instant Shortcode Builder: Integrate customizable UI features anywhere in your store - No coding knowledge required