Prestige theme add to cart button ajax on collection page and home page grid

AvidBrio
Shopify Expert
295 17 29

How to use the Prestige theme add to cart button ajax on the collection page and home page product item list?

 

 

  	<button type="submit" class="ProductForm__AddToCart Button {% if selected_variant.available and section.settings.show_payment_button == false %}Button--primary{% else %}Button--secondary{% endif %} Button--full" {% if selected_variant.available %}data-action="add-to-cart"{% else %}disabled="disabled"{% endif %}>
      {%- if selected_variant.available -%}
      {% if section.settings.add_cart_image %}
<!--       <div class="cart-img"><img src="{{ section.settings.add_cart_image | img_url: '28x28' }}" class="cart-img-display"/>
      <img src="{{ section.settings.add_cart_image_hover | img_url: '28x28' }}" class="cart-img-hover" /></div> -->
      <div class="cart-text"> 
        <span>{% if product.template_suffix == 'pre-order' %}{{ 'product.form.pre_order' | t }}
        {% else %}
        
        {{ 'product.form.add_to_cart' | t }}{% endif %}</span></div>
      {%- endif -%}

        {%- if section.settings.show_price_in_button -%}
          <span class="Button__SeparatorDot"></span>
          <span>{{ selected_variant.price | money_without_trailing_zeros }}</span>
        {%- endif -%}
      {%- else -%}
<!--       <div class="cart-img"><img src="{{ section.settings.add_cart_image | img_url: '28x28' }}" /></div> -->
        {{- 'product.form.sold_out' | t -}}
      {%- endif -%}
  	</button>

 

 

Theme js for add to cart code 

 

key: '_addToCart',
      value: function _addToCart(event) {
        var _this7 = this;

        if (!this.options['useAjaxCart']) {
          console.log("goes to cart page")
          return; // When using a cart type of page, we just simply redirect to the cart page
        }

        event.preventDefault(); // Prevent form to be submitted

        var addToCartButton = this.element.querySelector('.ProductForm__AddToCart');
        console.log("addToCartButton")
        // First, we switch the status of the button
        addToCartButton.setAttribute('disabled', 'disabled');
        document.dispatchEvent(new CustomEvent('theme:loading:start'));

        // Then we add the product in Ajax
        var formElement = this.element.querySelector('form[action*="/cart/add"]');

        fetch(window.routes.cartAddUrl + '.js', {
          body: JSON.stringify(__WEBPACK_IMPORTED_MODULE_2__helper_Form__["default"].serialize(formElement)),
          credentials: 'same-origin',
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest' // This is needed as currently there is a bug in Shopify that assumes this header
          }
        }).then(function (response) {
          document.dispatchEvent(new CustomEvent('theme:loading:end'));
          if (response.ok) {
            addToCartButton.removeAttribute('disabled');
            // We simply trigger an event so the mini-cart can re-render
            _this7.element.dispatchEvent(new CustomEvent('product:added', {
              bubbles: true,
              detail: {
                variant: _this7.currentVariant,
                quantity: parseInt(formElement.querySelector('[name="quantity"]').value)
              }
            }));
          } else {
            response.json().then(function (content) {
              var errorMessageElement = document.createElement('span');
              errorMessageElement.className = 'ProductForm__Error Alert Alert--error';
              errorMessageElement.innerHTML = content['description'];
              addToCartButton.removeAttribute('disabled');
              addToCartButton.insertAdjacentElement('afterend', errorMessageElement);
              setTimeout(function () {
                errorMessageElement.remove();
              }, 2500);
            });
          }
        });

        event.preventDefault();
      }

 

If you find our comment helpful, hit the like button and accept it as a solution.
Want us to implement custom changes in your store? Contact us
Email me directly - jim@avidbrio.com
Replies 8 (8)

LitExtension
Shopify Partner
4860 1001 1132

Hi @AvidBrio,

I checked and ajax cart only support product page, when you add code anywhere else it wont work. It's bundled by the theme and you can't edit it. https://i.imgur.com/AVM2OXc.png

So if you want ajax cart at item products you can just contact theme support or hire an expert.

Because it is a complex request and it is difficult for anyone to guide you in detail. You can post on the group, there will be many experts to help you: https://community.shopify.com/c/Jobs-and-Careers/bd-p/shopify-job-board

Hope it helps!

If my answer can help you solve your issue, please kindly mark it as a solution. Thank you and good luck.

LitExtension - Shopping Cart Migration Expert
Check out our Shopify migration app to migrate your online store to Shopify
AvidBrio
Shopify Expert
295 17 29

@LitExtension  thanks for your answer. community people also are the tech so don't pre assume that. if have the solution you can be posted into community it help other toos..

If you find our comment helpful, hit the like button and accept it as a solution.
Want us to implement custom changes in your store? Contact us
Email me directly - jim@avidbrio.com

Rohit_Sethi
Shopify Partner
3 0 1
<button type="submit" data-use-primary-button="{% if use_primary_button %}true{% else %}false{% endif %}" class="cstm_ad_to_cart Button {% if product.selected_or_first_available_variant.available and use_primary_button %}Button--primary{% else %}Button--secondary{% endif %} Button--full" var_id="{{product.selected_or_first_available_variant.id}}" {% if product.selected_or_first_available_variant.available %}data-action="add-to-cart"{% else %}disabled="disabled"{% endif %}></button>


Daniel-Anverso
Shopify Partner
12 0 8

Thanks for sharing this code, this one works on my Prestige. Here are some edits that I did:

I paste this code on "product-item.liquid", after the line 202:
<button type="submit" data-use-primary-button="{% if use_primary_button %}true{% else %}false{% endif %}" class="cstm_ad_to_cart Button {% if product.selected_or_first_available_variant.available and use_primary_button %}Button--primary{% else %}Button--secondary{% endif %} Button--full" var_id="{{product.selected_or_first_available_variant.id}}" {% if product.selected_or_first_available_variant.available %}data-action="add-to-cart"{% else %}disabled="disabled"{% endif %}>ADD TO CART</button>

 

Here's the JS code, you can put  it on the "custom.js" file:

$(document).on('click','.cstm_ad_to_cart',function(e){
e.preventDefault();
var ID = $(this).attr("var_id");
console.log(ID);
$.ajax({
type: 'POST',
url: '/cart/add.js',
data: {
quantity: 1,
id: $(this).attr("var_id")
},
dataType: 'json',
success: function (data)
{
document.dispatchEvent(new CustomEvent("product:added", {detail:{product:data}}));
}
});
});

Daniel-Anverso
Shopify Partner
12 0 8

Also, use Jquery and add it on your Theme.liquid

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

Octipus
Shopify Partner
30 2 7

This worked like a charm. Shame the solution uses jquery though but that's an acceptable compromise

- Was my reply helpful? Click Like to let me know!
- Was your question answered? Mark it as an Accepted Solution!

Tony_Rivas
Shopify Partner
1 0 0

Just solved this. All you need to do is edit the markup.

 

On your new block, on the main <section> tag you need to put this additional attributes, you can use all the classes you need, that does not matter:

 

 

<section class="your-class" data-section-type="featured-product" data-section-settings="{&quot;enableHistoryState&quot;: false,&quot;usePlaceholder&quot;: false,&quot;templateSuffix&quot;: &quot;&quot;,&quot;showInventoryQuantity&quot;: false,&quot;showSku&quot;: false,&quot;inventoryQuantityThreshold&quot;: 0,&quot;showPriceInButton&quot;: false,&quot;showPaymentButton&quot;: true,&quot;useAjaxCart&quot;: true}">
</section>

 

 

And the Form for adding a product needs to look something like this:

In this example my product field is called product_4, the class "ProductForm__AddToCart" is essential for it to work correctly.

 

 

{%- form 'product', section.settings.product_4, class: 'ProductForm' -%}
  {%- assign product = all_products[section.settings.product_4] -%}
  {%- render 'product-data', product: product -%}
  <button type="submit" data-use-primary-button="false" class="ProductForm__AddToCart" {% if section.settings.product_4.selected_or_first_available_variant.available %}data-action="add-to-cart"{% else %}disabled="disabled"{% endif %}>		
    {%- if section.settings.product_4.selected_or_first_available_variant.available -%}
        Add to cart
    {%- else -%}
        Sold Out
    {%- endif -%}
  </button>
  <input type="hidden" name="id" value="{{ section.settings.product_4.selected_or_first_available_variant.id }}">
{%- end-form -%}

 

 

The template will do the AJAX automatically now

Best of luck !

Octipus
Shopify Partner
30 2 7

This was my initial approach as well but it won't work if you use multiple products on the section. 

For example, my section is a product slider with multiple blocks of type product so i render a product -card snippet for each block.

Because this solution only takes in a Product, i had difficulty making it work and reverse engineering takes too much time for the job i need to do haha. 

 

I have also tried looking at "shop-the-look" section instead which helped but not much. 

 

- Was my reply helpful? Click Like to let me know!
- Was your question answered? Mark it as an Accepted Solution!