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

🌟Updated🌟 add multiple products with one button with the Ajax API using Fetch

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.

✨Shopify has made this a whole lot more straightforward than before!!✨

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

No longer using jQuery

Shopify no longer supports jQuery in their themes and with modern JavaScript options like Fetch, we don't really need it anymore anyway.

A button to add all the products to cart

We're going to add a button that will add all of the products in the Frontpage Collection to the cart.

To start, we make a button. 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 function, we'll be creating a little later in this tutorial, but right now we'll be setting up the input for it.

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


{% for product in collections['Frontpage'].products %}
  {{ product.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

Single fetch call to the AJAX API 🎉🎉🎉

This is where our lives have gotten a lot easier. We can now make a single call with multiple variant ids to the AJAX API. We'll also being using Fetch so we don't need any external libraries anymore either!

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

Once we've created a proper array, we then use the array method map to create a new array of objects that have the quantity and the variant id. In this case, we just use 1 for quantity, though we could also pass a different quantity value here as well. We then pass that array of objects to an object with the property items.

The end product will look something like this:


data = {
  items: [
    {
      id: 4004942227062
      quantity: 1
    },
    {
      id: 3374541147354
      quantity: 1
    },
    {
      id: 3968924929245
      quantity: 1
    },
    {
      id: 4004942135312
      quantity: 1
    }
  ]
}

We can then make a fetch POST call to the /cart/add.js endpoint.

We stringify the data object, pass it to the body of the call and voila ✨🙌✨ the items have been added to cart.


addAllItems(variantIdArray) {
  # split fake liquid array to make proper array
  var newVariantIdArray = array.split(',');

  # map over variant array to create an array of objects with quantity and id
  var product_data = newVariantIdArray.map(variantId => {
    return {quantity: 1, id: variantId}
  })

  # add the items to the data object we need to pass to the fetch call 
  var data = {
    items: product_data
  }
        
  fetch('/cart/add.js', {
    body: JSON.stringify(data),
    credentials: 'same-origin',
    headers: {
      'Content-Type': 'application/json',
      'X-Requested-With':'xmlhttprequest'
    },
    method: 'POST'
  }).then((response) => {
    return response.json();
  }).then((json) => {
    /* yay! our products were added - do something here to indicate to the user */
    console.log('products', json)
  }).catch((err) => {
    /* uh oh, we have error. */
    console.error(err)
  });
}

		
more posts