DEV Community

Cover image for liquid-ajax-cart.js — Ajax Carts for Shopify
EvgeniyMukhamedjanov
EvgeniyMukhamedjanov

Posted on • Updated on

liquid-ajax-cart.js — Ajax Carts for Shopify

Recently Shopify has released the amazing Sections API and Bundled Section Rendering in particular for Cart Ajax API requests.

It means we can update the cart state and ask Shopify to re-render the HTML code for specific sections within a single Cart Ajax API call:

let sectionsToUpdate = 'ajax-cart';

let requestBody = {
  'items': [{
    'id': 36110175633573,
    'quantity': 2
  }],
  'sections': sectionsToUpdate
};

fetch('/cart/add.js', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(requestBody)
}).then(response => {
  return response.json();
}).then(data => {
  console.log(data.sections); // prints HTML of the section 
}).catch((error) => {
  console.error('Error:', error);
});
Enter fullscreen mode Exit fullscreen mode

The above code sends an "Add to cart" request along with the section parameter so Shopify will respond with the new section's HTML that is printed by console.log.

The Liquid Ajax Cart Javascript library uses this method to update cart-related sections and saves you the hassle of writing the repeated JS-code for each project.

Theme section for the Ajax-cart

Create a new theme section that will be your Ajax-cart. There is only one requirement: the root container must have the data-ajax-cart-section attribute so Liquid Ajax Cart will be able to identify the section.

{% comment %} sections/my-cart.liquid {% endcomment %}

<div data-ajax-cart-section>
  <h2>My cart</h2>

  <div>
    {% for item in cart.items %}
    <div><a href="{{ item.url }}">{{ item.title }}</a></div>
    <div>Price: {{ item.final_price | money }} </div>

    <div>
      Quantity:
      <a data-ajax-cart-request-button
        href="{{ routes.cart_change_url }}?line={{ forloop.index }}&quantity={{ item.quantity | minus: 1 }}"> Minus one
      </a>
      <span>{{ item.quantity }}</span>
      <a data-ajax-cart-request-button
        href="{{ routes.cart_change_url }}?line={{ forloop.index }}&quantity={{ item.quantity | plus: 1 }}"> Plus one
      </a>
    </div>

    <div> Total: <strong>{{ item.final_line_price | money }}</strong> </div>
    <hr />
    {% endfor %}
  </div>

</div>

{% schema %} { "name": "My Cart" } {% endschema %}
Enter fullscreen mode Exit fullscreen mode

Include the section somewhere in the layout/theme.liquid file so it shows up on every page:

{% section 'my-cart' %}
Enter fullscreen mode Exit fullscreen mode

On this stage we have a static theme section for the cart.
The buttons Minus one and Plus one works but with page reloading.

Ajaxifing

Upload the liquid-ajax-cart.js into the assets folder of your store and include it in the layout/theme.liquid file:

<!-- It is for receiving the initial state -->
<script type="application/json" data-ajax-cart-initial-state >
  {{ cart | json }}
</script>

<script type="module">
  import '{{ "liquid-ajax-cart.js" | asset_url }}';
</script>
Enter fullscreen mode Exit fullscreen mode

And... that's it!

Liquid Ajax Cart will ajaxify all product form, the routes.cart_change_url buttons and will update the cart section's HTML every time when a user submits a product form or clicks the Plus one, Minus one links.

Сonclusion

Just two steps are enough for the quick start and understanding how it works. All the features are described on the documentation website.

Feel free to ask questions.

Top comments (0)