skip to Main Content

I’m trying to update the Shopify cart onclick. It’s working but when I try to update cart count without page refresh with cart add success: function it’s not working. Below is my code.

$(function(){
    $('.varients-item').on('click', function(){
        var obj = $(this);
        $.ajax({
            type: 'POST',
            url: '/cart/add.js',
            data: {
                quantity: 1,
                id: $(this).attr("data-variant")
            },
            dataType: 'json',
            success: function (data) {  
                //alert('Item added to cart');
                $('.cart-item-count').html(cart.item_count);
            }
        });
    });
});

Here is the console error:

enter image description here

2

Answers


  1. Chosen as BEST ANSWER

    Here is my solution.

    $(function(){
        var cartCount = {{ cart.item_count }};
        $('.varients-item').on('click', function(){
            var obj = $(this);
            $.ajax({
                type: 'POST',
                url: '/cart/add.js',
                data: {
                    quantity: 1,
                    id: $(this).attr("data-variant")
                },
                dataType: 'json',
                success: function (data) {
                    $.ajax({
                        type: 'GET',
                        dataType: 'json',
                        url: '/cart.json',
                        success: function(cart){
                            cartCount++;
                            $('.cart-item-count').html(cartCount);
                        }
                    });
                }
            });
        });
    });
    

  2. Well you are calling cart.item_count, but cart is not defined. It’s written in the error response.

    You are passing data as the callback argument here success: function (data), so you should call data.item_count instead.

    BUT cart/add.js does not return the JSON for the cart, but the added product JSON. You need to make a second request to cart.js in order to get the cart object!

    So your code should look something like this:

    $(function(){
      $('.varients-item').on('click', function(){
          var obj = $(this);
          $.ajax({
              type: 'POST',
              url: '/cart/add.js',
              data: {
                  quantity: 1,
                  id: $(this).attr("data-variant")
              },
              dataType: 'json',
              success: function () {  
                  $.ajax({
                    url: '/cart.js',
                    success: function(cart){
                      $('.cart-item-count').html(cart.item_count);
                    }
                  })
              }
          });
      });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search