I’m trying to update the Shopify cart onclick
. It’s working but when I try to update cart count without page refresh with cart add success: function
it’s not working. Below is my code.
$(function(){
$('.varients-item').on('click', function(){
var obj = $(this);
$.ajax({
type: 'POST',
url: '/cart/add.js',
data: {
quantity: 1,
id: $(this).attr("data-variant")
},
dataType: 'json',
success: function (data) {
//alert('Item added to cart');
$('.cart-item-count').html(cart.item_count);
}
});
});
});
Here is the console
error:
2
Answers
Here is my solution.
Well you are calling
cart.item_count
, butcart
is not defined. It’s written in the error response.You are passing
data
as the callback argument heresuccess: function (data)
, so you should calldata.item_count
instead.BUT
cart/add.js
does not return the JSON for the cart, but the added product JSON. You need to make a second request tocart.js
in order to get the cart object!So your code should look something like this: