How to use the Prestige theme add to cart button ajax on the collection page and home page product item list?
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();
}
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 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..
<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 %}>
1 Like
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
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}}));
}
});
});
1 Like
Also, use Jquery and add it on your Theme.liquid
Just solved this. All you need to do is edit the markup.
On your new block, on the main tag you need to put this additional attributes, you can use all the classes you need, that does not matter:
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 -%}
{%- end-form -%}
The template will do the AJAX automatically now
Best of luck !
This worked like a charm. Shame the solution uses jquery though but thatâs an acceptable compromise
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.