Updating the Cart Drawer using the Ajaxify Cart API

Highlighted
Shopify Partner
3 0 0

Hi all, 

I am building a site and also building in my first Ajaxify-Cart.  So I have successfully got the script working to update the cart count and then open the cart drawer, but the contents of the cart drawer will not start working until I refresh the page. I have tried re-odering my scripts in the Theme.liquid to see if ajaxify-cart.liquid needed to be above my cart JS file, but this didn't solve it.  Once the page has been refreshed, I can then add a product to the cart and the drawer slides open and updates fine.  So I am sure I am just missing sometihing simple - maybe I am calling the update cart script wrongly in the Ajaxify-Cart.liquid - a lot of this has been achieved by adapting methods I have seen in other themes!

The Ajaxify Cart scipt section I have updated to call the cart JS file (I commented my additions - my thoughts was to call this where the normal succes happens:

// Add to cart.
        $.ajax({
          url: _config.shopifyAjaxAddURL,
          dataType: 'json',
          type: 'post',
          data: $addToCartForm.serialize(),
          success: function(itemData) {
            // Re-enable add to cart button.
            $addToCartBtn.addClass('inverted');
            _setText($addToCartBtn, _config.addedToCartBtnLabel);
            //_showFeedback('success','<i class="fa fa-check"></i> Added to cart! <a href="/cart">View cart</a> or <a href="/collections/all">continue shopping</a>.',$addToCartForm);
            
            
            
            window.setTimeout(function(){
              $addToCartBtn.prop('disabled', false).removeClass('disabled').removeClass('inverted');
              _setText($addToCartBtn,_config.addToCartBtnLabel);
            }, _config.howLongTillBtnReturnsToNormal);
            // Update cart count and show cart link.
            
            $.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');
              }
              if (_config.cartTotalSelector && $(_config.cartTotalSelector).size()) {
                if (typeof Currency !== 'undefined' && typeof Currency.moneyFormats !== 'undefined') {
                  var newCurrency = '';
                  if ($('[name="currencies"]').size()) {
                    newCurrency = $('[name="currencies"]').val();
                  }
                  else if ($('#currencies span.selected').size()) {
                    newCurrency = $('#currencies span.selected').attr('data-currency');
                  }
                  if (newCurrency) {
                    $(_config.cartTotalSelector).html('<span class=money>' + Shopify.formatMoney(Currency.convert(cart.total_price, "{{ shop.currency }}", newCurrency), Currency.money_format[newCurrency]) + '</span>');
                  } 
                  else {
                    $(_config.cartTotalSelector).html(Shopify.formatMoney(cart.total_price, "{{ shop.money_format | remove: "'" | remove: '"' }}"));
                  }
                }
                else {
                  $(_config.cartTotalSelector).html(Shopify.formatMoney(cart.total_price, "{{ shop.money_format | remove: "'" | remove: '"' }}"));
                }
              };
            });  

// NEW CODE
                                                    
            $.getJSON("/cart.js", function(cart) {
            	refreshCart(cart);
            });  
                
            openDrawer();

// END
                
          }, 
          error: function(XMLHttpRequest) {
            var response = eval('(' + XMLHttpRequest.responseText + ')');
            response = response.description;
            if (response.slice(0,4) === 'All ') {
              _showFeedback('error', response.replace('All 1 ', 'All '), $addToCartForm);
              $addToCartBtn.prop('disabled', false);
              _setText($addToCartBtn, _config.soldOutBtnLabel);
              $addToCartBtn.prop('disabled',true);
            }
            else {
              _showFeedback('error', '<i class="fa fa-warning"></i> ' + response, $addToCartForm);
              $addToCartBtn.prop('disabled', false).removeClass('disabled');
              _setText($addToCartBtn, _config.addToCartBtnLabel);
            }
          }
        });   
        return false;    
      });

 

And the script I have in the other file:

//******Cart Updating Stuff *****

function ajaxSubmitCart() {
  $cart = $("#cart");
  $.ajax({
    url: '/cart.js',
    dataType: 'json',
    type: 'post',
    data: $cart.serialize(),
    success: function (data) {
      refreshCart(data);
    }
  });
}
 function refreshCart(cart) {
   
    $cartBtn = $(".cart-drawer-count");
    if ($cartBtn && $cartBtn.size()) {
      var value = $cartBtn.text() || '0';
      var cart_items_html = "";
      var $cart = $("#cart ul");
      
      $cartBtn.text(value.replace(/[0-9]+/,cart.item_count));
      $cart.find('li:not(:first)').remove();

      if (cart.item_count == 0) {
        $cart.append('<li class="empty_cart">{{ 'layout.general.empty_cart' | t }}</li>');
      } else {
        $.each(cart.items, function(index, item) {
          if(item.formatted_recurring_desc === undefined)
            item.formatted_recurring_desc = "";
          cart_items_html += '<li class="cart_item clearfix">';
            if (item.image) {
              cart_items_html += '<div class="cart_image">' +
                  '<img src="' + item.image.replace(/(\.[^.]*)$/, "_medium$1").replace('http:', '') + '"  />' +
                '</div>';
            }
            '<div class="cart_item__title">' +
              '<div class="item-deet-wrap">' +
              '<div class="item_title">' + item.title + item.formatted_recurring_desc +'</div>';
          cart_items_html += '<div class="item_title">' + item.title + item.formatted_recurring_desc +'</div>' +
              '<div class="qty-wrapper">' +
                  '<input type="button" value="-" class="qtyminus" field="quantity" />' +
                  '<input type="text" id="Quantity" name="quantity" value="'+ cart.item_count +'" class="product-form__input qty" />'+
                  '<input type="button" value="+" class="qtyplus" field="quantity" />'+
                  '</div>'+
            	  '<div class="right price">'+
                  '<span class="money">' + Shopify.formatMoney(item.price, $cart.data('money-format')) + '</span>'+
                '</div>'+
          '</li>';
        });

        cart_items_html += '<li class="mm-label">' +
            '<p class="mm-counter">' + Shopify.formatMoney(cart.total_price, $cart.data('money-format')) + '</p>' +
            '<a href="/cart">' +
              '<strong>{{ 'cart.general.subtotal' | t }}</strong>' +
            '</a>' +
          '</li>' +
          '<li class="mm-subtitle clearfix">';

          

          cart_items_html += '<div class="center-me">' +
          	'<input type="submit" name="checkout" class="action_button btn" value={{ 'cart.general.checkout' | t | json }} />' +
            '</div>';
          '</li>';

        $cart.append(cart_items_html);
        $cart.find('li.cart_item:last').addClass('last_cart_item');
        
      }
      
    }
   		
  }

$(document).on("change", "#cart input.quantity", function() { 
  ajaxSubmitCart();
});

$(document).on("click", ".qtyminus", function() { 
  var quantity = parseInt($(this).next("input").val()); 
  quantity -= 1;
  $(this).next("input").attr("value", quantity);
  if (quantity == 0) {
    $(this).closest('li.cart_item').addClass('animated fadeOutUp')
    setTimeout(ajaxSubmitCart, 500);
  } else {
    ajaxSubmitCart();
  }
});
$(document).on("click", ".qtyplus", function() { 
  var quantity = parseInt($(this).prev("input").val()); 
  quantity += 1;
  $(this).prev("input").attr("value", quantity);
  ajaxSubmitCart();
});

function openDrawer(){        
	$("#cart-drawer").addClass("open");
}

 

The updating of the values with the qtyminus and qtyplus, update the correct text field for a moment, but then revert back, so it is like the cart is not refreshing for me - Any help would be great thanks!

 

 

0 Likes
Highlighted
Shopify Partner
3 0 0

AMEND: I pasted wrong, the first code actually has this section:

// NEW CODE
                                                    
            $.getJSON("/cart.js", function(cart) {
            	ajaxSubmitCart();
            });  
                
            openDrawer();

// END

 

0 Likes
Highlighted
New Member
1 0 0

Dave,

Did you find a solution?  I have the EXACT same issue here;

https://www.werunthistown.com

Cart Drawer is not updating.  Would appreciate your help if you got it, or somebody else to help us both :)

0 Likes
Highlighted
Shopify Partner
11 0 1

Dealing with the same issue, any progress with this?

0 Likes
Highlighted
New Member
4 0 0

Dave,

Did you find a solution?  I have the EXACT same issue.

 

Cart Drawer is not updating.  Would appreciate your help if you got it, or somebody else to help us.

0 Likes
Highlighted
New Member
2 0 0

Did anyone find a solution for this issue. I keep finding pages talking about this issues. But no solution....

0 Likes