Update cart contents counter after Ajax update

A short post that will hopefully be helpful to somebody – I’ve had to write this because Shopify have an annoying policy of closing old forum threads when it’d be more useful to keep them open and have them updated.

This thread;

https://ecommerce.shopify.com/c/shopify-apis-and-technology/t/how-do-i-update-the-cart-counter-immediately-via-ajax-268966

Has an outdated solution for the problem.

Problem

If you enable the Ajax updating in the drawer / minicart in Shopify you can update the quantities of the individual items in the cart. But you may have a small cart total items icon in your link to that minicart – how to update that without a page refresh?

The Solution Part 1 – Collections page

If you have add to cart buttons on the collections page you need to modify the file assets/ajax-cart.js.liquid. Specifically the adjustCartCallback method.
adjustCartCallback = function (cart) {
  // Update quantity and price
  updateCountPrice(cart);

  // This is the new line that updates the cart counter
  $('.cart-counter').html(cart.item_count);

  // Reprint cart on short timeout so you don't see the content being removed
  setTimeout(function() {
    isUpdating = false;
    ShopifyAPI.getCart(buildCart);
  }, 150)
};

The Solution Part 2 – Product page

Assuming you’ve Ajaxified the product view page using this guide » , then you’d update the snippets/ajaxify-cart.liquid template and specifically the Ajax success callback;

$.getJSON(_config.shopifyAjaxCartURL, function (cart) {
    if (_config.cartCountSelector && $(_config.cartCountSelector).size()) {
        var value = $(_config.cartCountSelector).html() || '0';
        $(_config.cartCountSelector).html(value.replace(/[0-9]+/, cart.item_count)).removeClass('hidden-count');
    }

    $('.cart-counter').html(cart.item_count);