AJAX and Data Attributes

LemonStand offers a built-in AJAX framework that makes sending requests to the server and updating page elements asynchronously a breeze.

Let's have a look at an example of AJAX and data attributes in action in the default install of your LemonStand store.

Start by logging in to the backend of your store, and click on the Store Design link in the sidebar. Then open the Partials section.

In the Partials section find the partial named shop-cart-content and click on it to edit.

First a little explanation on what the shop-cart-content partial does. The shop-cart-content partial is basically the template for the shopping cart page. It contains a call to render the shop-cart-items partial as well as the shipping rates and order total calculator. The shop-cart-content partial also contains a block of buttons at the bottom, where you will see the continue shopping, coupon code, update cart and checkout buttons.

This button block is the area that we will be referencing for our example.


In the Content area of the shop-cart-content partial, find the following line of code, which should be located on line 60.

<code class="language-twig"><a href="#" data-ajax-handler="shop:cart" data-ajax-update="#cart-content=shop-cart-content, #mini-cart=shop-minicart">Update cart</a></code>

This snippet of code is for the update cart button. The update cart button will update the cart page based on any changes you have made to the cart since the page was originally loaded. Such as changing the quantity amount of an item in your cart.

There are two attributes that make up our AJAX functionality, data-ajax-handler and data-ajax-update.

The data-ajax-handler will refer to the CMS AJAX handler that will process the request on the server, in this case it would be the shop:cart AJAX handler.

The data-ajax-update attribute refers to the page element that will be updated after the server processes the request. This is broken up into two sections. The CSS selector for the element that wraps the content that you want to be updated and the partial that renders the actual content to be updated.

In this case, for example, you can see the following for data-ajax-update:

<code class="language-twig">data-ajax-update="#cart-content=shop-cart-content, #mini-cart=shop-minicart"</code>

From this snippet we can see that there are two areas being updated when the update cart button is clicked. First we update the shop-cart-content partial which is rendered within a DIV with an ID of cart-content. Then we update the mini-cart which is rendered within the shop-minicart partial that is contained within a DIV with the ID of mini-cart