Code Shopify About

Shopify App and Theme Development tutorials for those who are familiar with code and want to dive into Shopify.

Sign up for Shopify

How to add multiple products with an AJAX cart

Friday, Aug 06, 2021

There may be times when you have a use case for adding multiple products to the Shopify cart with just one button. This could if you like to add an "buy this outfit" button or if you'd like to include a "buy the entire collection" button.

In this tutorial we're going to show you how to add a Buy this collection button with AJAX.

Make sure the Shopify JavaScript is included

Shopify has a bunch of JavaScript files that provide specific functionality to the stores. Make sure these files as well as jquery is linked to your store before starting this tutorial.


{{ "option_selection.js" | shopify_asset_url | script_tag }}
{{ "shopify_common.js" | shopify_asset_url | script_tag }}
{{ "customer_area.js"  | shopify_asset_url | script_tag }}
{{ "//cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js" | script_tag }}

Add a link to the cart with item count

First we're going to add a View Cart button to the page. This is a link that goes to /cart which is the shopify cart page. It shows the customer the item count in cart and this will be updated as through AJAX for the multiple products being updated.

Make sure that it has an id of cart-number, we'll be using that as a jQuery selector.


View cart : {{cart.item_count}}

A button to add all the products to cart

Now we're going to add a button that will add all of the products in the Frontpage Collection all at once.

To start, we make a button with the type submit. We add an id of "add-{{ collections['Frontpage'].id }}", this will create and id that equals add-328971974 (or whatever your frontpage collection id may be).

Then on the onclick we call a function addAllItems. This functions we'll be creating a little later in this tutorial, but right now we'll be setting up the input for the function.

I'll break out the loop for grabbing all the product ids for readability. Here you'll see we're using the liquid for loop and then adding the products selected or first variant. Then we'll add a , to separate then and use the unless forloop.last syntax to skip the last one.


{% for product in collections['Frontpage'].products %}
	{{ product.selected_or_first_available_variant.id }}
	{% unless forloop.last %},{% endunless %}
{% endfor %}

The output of the loop will look something like this (but with your own product ids of course)


26654534406,26654522182,26654539398,26654529798,26654525830,26654523398,26654537222,26654518406,26654538950

Here's all the code for the button together.



The JavaScript

Shopify.queue

The tricky thing with adding multiple products with Shopify is that although you use AJAX, the call actually must be synchronous. If the call is not synchronous, unexpected results could occur.

For this reason we use a built in option call the Shopify.queue. We set the value as an array and we push each product one by one in with a for loop.

Also, note that since Liquid doesn't have proper arrays, we must first set a newArray variable that is split on the comma.

Then we set the moveAlong function in the Shopify namespace. This function has the AJAX call to add each product one by one and works essentially as a loop. If the AJAX call is successful, we add one to the the quantity and call the moveAlong function again. If there are products left in the queue it loops again, otherwise it adds one more to quantity and calls the addToCartOk function, which updates the View Cart with the current number.

If any given product fails, it calls the moveAlong function again or if there's nothing left in the queue it updates the View Cart. Probably you'd want to alert the user of the error in some way. I chose to leave that out to keep the code as simple as possible.


function addAllItems(array){
	Shopify.queue = [];
	  var quantity = {{ cart.item_count }} ;
	  var newArray = array.split(',');
	  for (var i = 0; i < newArray.length; i++) {
	    product = newArray[i]
	    Shopify.queue.push({
	      variantId: product,
	    });
          }
	  Shopify.moveAlong = function() {
	  // If we still have requests in the queue, let's process the next one.
	  if (Shopify.queue.length) {
	    var request = Shopify.queue.shift();
	    var data = 'id='+ request.variantId + '&quantity=1'
	    $.ajax({
	      type: 'POST',
              url: '/cart/add.js',
	      dataType: 'json',
	      data: data,
	      success: function(res){
	        Shopify.moveAlong();
		  quantity += 1;
	     },
             error: function(){
	     // if it's not last one Move Along else update the cart number with the current quantity
		  if (Shopify.queue.length){
		    Shopify.moveAlong()
		  } else {
		    $('#cart-number').replaceWith("View cart (" + quantity + ")")
		  }
	      }
           });
        }
	 // If the queue is empty, we add 1 to cart
	else {
	  quantity += 1;
	  addToCartOk(quantity);
	 }
       };
    Shopify.moveAlong();
  };

Successful Add to Cart

The add to cart function selects the View Cart link with it's id and updates it with the current quantity once all the AJAX calls have been made and


function addToCartOk(quantity){  
	$('#cart-number').replaceWith("View cart (" + quantity + ")");
} 
more posts