Shopify update cart.item_count using AJAX

戏子无情 提交于 2020-01-03 05:24:10

问题


On the product detail page of my Shopify site when you click "Add To Cart" the page uses AJAX to do its thing. BUT there is a variable named cart.item_count that does not update unless the page refreshes.

Question: How to get AJAX to update the cart.item_count on that page.

Below is the code for the HTML page:

        <div id="mini-cart" >

            <span class="cart_count_info">Cart ({{ cart.item_count }})</span>//THIS SPAN IS WHAT NEEDS TO BE UPDATED 

        </div>

         <p id="add-to-cart-msg"></p> //THIS "P" IS UPDATED BY THE AJAX WITH MESSAGING SEE BELOW JAVASCRIPT

          <form action="/cart/add" method="post" class="variants" id="product-actions" enctype="multipart/form-data">
              //TOOK OUT SOME OF THE FORM DATA THAT IS NOT NEED FOR THIS EXAMPLE

          </form>

JavaScript Code. There is a line of code at the bottom that updates some copy on the same page... If I can update my cart.item_count variable that is already found on he page.

function addToCartSuccess (jqXHR, textStatus, errorThrown){

  $.ajax({
    type: 'GET',
    url: '/cart.js',
    async: false,
    cache: false,
    dataType: 'json',
    success: updateCartDesc
  });
  $('#add-to-cart-msg').hide().addClass('success').html('Item added to cart! <a href="/cart" title="view cart">View cart and check out &raquo;</a>').fadeIn();

$('span#cart_count_info').load(Cart ({{ cart.item_count }})); 
//MAYBE HERE IS WHERE I CAN ADD MY CODE TO UPDATE THE VARIABLE I NEED. MY CODE IS JUST A GUESS SINCE ID DON'T DO MUCH JAVASCRIPT PROGRAMMING.


}

回答1:


Remove

$('span#cart_count_info').load(Cart ({{ cart.item_count }})); 

and replace it for "UpdateCartDesc" function bellow (see your success message)

function updateCartDesc(data){
  var $cartLinkText = $('.cart_count_info').html(data.item_count);
}



回答2:


Taking it as its related to header when you click Add to Cart, you get the updated number of products in your Cart.

Just add class cart-count to the div. Your structure should look like this:

#pageheader > .cart-summary > .cart-count


来源:https://stackoverflow.com/questions/17387667/shopify-update-cart-item-count-using-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!