skip to Main Content

I’m trying to get around the Shopify Cart API. I’m currently using the newest Shopify Sense theme, and using the Cart Drawer as cart page. Here is a gist of the cart-drawer.js file, which looks like this (https://gist.github.com/OsaraCode/613e4baecb5a318bdb2b0a2d89532ee2), and the cart.js file which controls all cart actions (updating quantities, etc) on both cart page and cart drawer (https://gist.github.com/OsaraCode/daf3392b5167713b88adae2f9ff8d2c8). What I have been trying to achieve, is building some product upsell boxes inside Cart Drawer, and then when clicking "add", it adds the product to the cart and refreshes the cart drawer. Adding the product to the cart, works fine – this is my code:

$( document ).ready(function() {

  
Shopify.addToCart = function(items) {
    fetch(window.Shopify.routes.root + 'cart/add.js', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(items)
  })
  .then(response => {
    return response.json();
    console.log("product successfully added to cart");
  
  }).then((state) => {

    console.log("Current State: " + state)
  })
  .catch((error) => {
    console.error('Error:', error);
  });
};
  $( ".upsell_atcButton" ).on( "click", function() {
console.log("Clicked")
      let upsellProductId = $(this).data("variant-id");
      console.log("Variant ID: " + upsellProductId);
      let products = {
       'items': [{
          'id': upsellProductId,
          'quantity': 1
        }]
      };
    console.log("Products: " + products)
    Shopify.addToCart(products);
  });
  
});

I just can’t get my head around how to make refresh the cart. The product gets added, because even though my cart doesnt rerender, hard refreshing the site makes the product appear.

I hope any of you can point me in the correct direction, or share any possible solutions you have used in your own projects.

Thank you very much in advance!

2

Answers


  1. $.ajax({
                    url: '/?section_id=cart-drawer',
                    type: 'GET',
                    dataType: 'html',
                    success:function(carthtml) {
                      $('cart-drawer').html($(carthtml).find('cart-drawer').html());
                    }
                  });
    

    You can only add this ajax code here( https://prnt.sc/gj4Fg5dfkWrC ) in your code.

    Login or Signup to reply.
  2. Add this code when add or update function successfully done in Prestige theme

    document.dispatchEvent(new CustomEvent(‘cart:build’ , {bubbles: true}));
    document.dispatchEvent(new CustomEvent(‘cart:refresh’, {
    bubbles: true,
    detail: cartData
    }));

    Add this code when add or update function successfully done in broadcast theme
    window.cart.getCart();
    document.querySelector(‘.iCartBtnToggle’).click();

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search