All Tutorials

Interact with the Ajax API using jQuery

All Tutorials

Interact with the Ajax API using jQuery

Interact with the Ajax API using jQuery

This tutorial describes ways of interacting with Shopify's Ajax API using jQuery when developing themes for the Online Store. Note that you don’t have to use jQuery to interact with the APIs. Instead, you could use modern native web APIs such as fetch or your preferred browser HTTP client library.

A simple example using jQuery

This simplified code snippet illustrates how you could update an HTML element with the current number of items in the cart.

There are <span class="cart-item-count"></span> item(s) in your cart.

<script>
  var cartItemCounter = document.querySelector('span.cart-item-count');

  jQuery.ajax({
      url: '/cart.js',
      dataType: 'json'
    })
    .done(function(data){
      var newCount = data.item_count;
      cartItemCounter.innerText = newCount;
    });
</script>

Using Shopify’s jQuery wrapper library

You can use Shopify's jQuery wrapper library to work with the Ajax API. This library allows you to access convenience functions in your scripts through a Shopify variable attached to the browser's window object. For example, Shopify.clear() will clear the contents of the shopping cart.

Explore the interactive documentation site to learn how to use the Ajax API jQuery wrapper.

To enable the wrapper library in your online store, include these Liquid tags in your theme to render the required <script> elements:

{{ '//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js' | script_tag }}
{{ 'api.jquery.js' | shopify_asset_url | script_tag }}