AJAX cart count

Highlighted
Tourist
17 0 0
I am making my add to cart button update a span counter of items in the cart which works every time after you click the button once but does not work on the first click

I have tried using .on method which gives the same outcome and have tried using document.ready which also doesn't effect it.

$(document).ready(function() {
$("#addToCart").click(function(){

jQuery.getJSON('/cart.js', function(cart) {
$("span.count").html(cart.item_count);
});
});
});

I expect the addToCart button to update the span.count on every click. The actual result is that it works after the first click.

0 Likes
Highlighted
Shopify Expert
9926 103 1765

A little hard to give advice here as there's no a live version to see.

If I was to guess, you've now got two events bound to the button.

  1. One being the actual add to cart.
  2. The other being your function.

 

Is it possible that the first call fails since there's nothing in the cart (aka, your function fired before the add to cart call)?

If you're not sure about this you can watch the network logs in your browser debug console.

 

Really you should be waiting until the add to cart event has finished before calling the cart count update function. You may even be able to tap into the existing callbacks vs making a brand new click event.

★ Winning Partner of the Build a Business competition. ★ http://freakdesign.com.au
1 Like
Highlighted
Tourist
17 0 0

Hi Jason thanks for your reply, I managed to get it working by changing the CartSelector in the ajaxfy var conifg by just changing the class/id it was selecting however I do still have one problem, our website is univarsc.com. The one problem I seem to have now is that the ajax button seems to work only once the page is fully loaded so if a user was to go onto a product page and press add to cart asap then it still redirects the ajax only works once you let the page fully load

0 Likes
Highlighted
New Member
6 0 0

Hi Brad, 

 

Is it possible for you to walk me through your corrections to the Ajaxify.cart . I have the same issue. When I arrive on my website the cart count isn't showing (even if there is still items in the cart from my last visit), and I need to add a new item to the cart to see de cart count appear. 

 

Thank you!

0 Likes