How Do I Update the Cart Counter Immediately via AJAX?

Highlighted
Tourist
6 0 2

Hi,

 

I need to access cart.item_count to update the cart counter on a click event, but despite much research, haven't found a helpful example.

 

Here's the scenario:

On the homepage, Jane adds an item to her cart. Without reloading the page, Jane can view the cart in a slide-out drawer and see the items she's added. The cart counter should follow suit, but this comes back undefined: 

Shopify.onItemAdded = function(cart) {
  	alert('There are now ' + cart.item_count + ' items in the cart.');
};

This updates the counter successfully, but only with the number of items just added—not the total items in the cart:

Shopify.addItem(variant_id, quantity, function(line_item){
   console.log(line_item);
});

Finally, here's the simple method I'm using to add items to the cart:

<a href="#" onclick="Shopify.addItem(jQuery('#add_item{{product.id}}').val(), jQuery('#add_item_qty').val()); return false" class="btn highlight add-to-cart"><span class="btn-text">Add To Cart</span></a>

 

In Summary…

Where can I find an example of how to handle this simple scenario? How exactly does one acces the cart.item_count via the Shopify API? I'd be so grateful if someone could outline how this is done or point me in the direction of more complete documentation. 

 

Thanks,

L

 

0 Likes
Shopify Staff (Retired)
Shopify Staff (Retired)
143 0 24

Hi Lindsey,

You can find documentation for the Ajax API here: https://docs.shopify.com/support/your-website/themes/can-i-use-ajax-api

The /cart/add.js response only contains the line item, but you can always get the complete cart using /cart.js — something like this should work:

 jQuery.getJSON('/cart.js', function(cart) {
  alert('There are now ' + cart.item_count + ' items in the cart.');
} );

The entire cart is also returned if you use /cart/update.js instead of /cart/add.js. 

0 Likes
Tourist
6 0 2

Hi Josh, 

 

Thanks so much! That's exactly what I needed. 

 

For anyone reading this down the road, here's the code:

 

Shopify.onItemAdded = function(cart) {
	jQuery.getJSON('/cart.js', function(cart) {
  		$('#cartCount').html(cart.item_count);
	});
};

 

1 Like