Skip to content

Instantly share code, notes, and snippets.

@bjornbennett
Created May 3, 2018 02:48
Show Gist options
  • Select an option

  • Save bjornbennett/695db8f004caa574e7ca1f2035259471 to your computer and use it in GitHub Desktop.

Select an option

Save bjornbennett/695db8f004caa574e7ca1f2035259471 to your computer and use it in GitHub Desktop.
Shopify Liquid / jQuery - Get cart item count
// on anchor click, after 300ms, fetch cart count.
$('a').click(function(){
setTimeout(function(){
$.getJSON('/cart.js', function(cart){
var result = cart.item_count;
console.log(result);
});
},300);
});
@gelsas

gelsas commented Dec 10, 2020

Copy link
Copy Markdown

Can I get the current item count in the customers cart with this?

What I am trying to achieve is:

  1. Get current customer cart Item count
  2. If item count 2 set discount cookie to 25OFF
  3. If item count 3 set discount cookie to 30OFF

Is first step of this possible with this script?

@bjornbennett

bjornbennett commented Dec 14, 2020 •

Copy link
Copy Markdown
Author

Sure does. The JSON call still retrieves the .item_count. You can test it out here at this test store:
https://loft-theme-demo-nashville.myshopify.com/products/squared-padded-chair. Add some items to the cart, and paste this into the dev console:
setTimeout(function(){ $.getJSON('/cart.js', function(cart){ var result = cart.item_count; alert(result + ' items in cart.'); }); },500);

@zalivavit

Copy link
Copy Markdown

Thanks for that script! Really helpful!
Why we use here setTimeout?

@bjornbennett

Copy link
Copy Markdown
Author

Thanks for that script! Really helpful!
Why we use here setTimeout?

@zaliVAT No problem! I believe I was having issues with it firing too soon maybe (can't remember!), so I delayed it by 300ms. You could easily remove it and if it works, you'll probably be fine. Just remove line 4 & 9 and you're good to go.

@MurukanK

Copy link
Copy Markdown

Hi @bjornbennett

I used your code.
But its show an error
Access to XMLHttpRequest at 'https://shop.test.co.nz/cart.json' from origin 'https://testDomain.nz' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

@bjornbennett

bjornbennett commented Mar 23, 2023 •

Copy link
Copy Markdown
Author

Hmm not sure why you're getting an error for cart.json, although the code sends an AJAX request to cart.js. Are you sending an AJAX request to cart.json instead? Typo maybe? I just tried it again on the link above and it appears to still be functional.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment