简体   繁体   中英

Updating the cart number in Shopify with AJAX

Apologies if this is somewhere else but I can't find a better way of doing this.

I want to update the cart total number in realtime with AJAX anytime a product is added, removed, or quantity is changed.

I have it working but there has to be a better way. It feels wrong to poll constantly for changes and I certainly don't want to end up with a memory leak.

Right now I have the item count being fetched from JSON and then changing the number in the div by polling every second, giving the user the illusion that the number is being updated when they change something.

I've tried adding a listener to the add to cart button (works) as well as listening on the quantity selector (doesn't work).

I'm sure I'm just being a noob so any help is appreciated. Code below:

// Fetch the cart in JSON and change cart quantity on the fly after first product added to cart
  function doPoll(){
    setTimeout(function() {
      $.getJSON('/cart.js', function(cart) {
        $('.cart-count').html(cart.item_count);
        doPoll();
    }, 1000);
  }

Update

So the fix was actually very simple. The reason I couldn't attach a listener on a particular element within the cart was the cart wasn't loaded yet via ajax (duh!)

So all I did was remove the constant polling and instead ran my function anytime the ajax on the page was fully loaded:

$( document ).ajaxComplete(function() {
    //Do stuff here
});

Actually it's even simpler. If an ajax driven cart adjustment happens Timber gives you an overridable hook. Just override ShopifyAPI.onCartUpdate

eg

ShopifyAPI.onCartUpdate = function(cart){
    //do something new with the cart contents
    $('.cart-count').html(cart.item_count);
};

Other than that your cart count is also available on page load via liquid so if you combine the two you're covered:

<div class="cart-count">{{ cart.item_count }}</div>

If you have not implemented any other way to add to cart, it's very simple.

If you look in the AJAX functions file you have mentioned, especially in functions at lines 101 and 113, you can see that those function are related to cart update. Add your code $('.cart-count').html(cart.item_count); before callback(cart); and you'll be good to go.

A more up to date solution without Jquery. You can use fetch and then use the data returned to populate the cart count.

      fetch('/cart.js')
      .then(response => response.text())
      .then((responseText) => {
        data = JSON.parse(responseText);
        var counterEl = document.querySelectorAll('.js-cart-item-count');

        counterEl.forEach((element) => {
          element.innerHTML = data.item_count
        })
      })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM