Submit multiple Product variants in Shopify

shopify-e-commerce-software-1

Shopify is a great e-commerce platform which allows you to setup your own store fast. If you look at Shopify themes, almost of theme support your customer to quickly add A PRODUCT to the cart. But, in many cases, you might want to allow customer to quickly select multiple products, or multiple variants of a product on a page. Like this one

Screen Shot 2018-08-22 at 15.02.22.png

Then, you go to Shopify Apis, do a quick search, you can come to a solution to use Ajax call here. The problem is, it does not tell you in detail how to do it in your liquid template.

First, as the Shopify Api documentation says,

You cannot add different variants to the cart with a single Ajax request. You’ll need to queue up several Ajax requests synchronously to add different variants to the cart.

Thus, I come up with a solution to add variants single by single to the card use Ajax. You can take a look at below example code

// Assumes that you have a way to collect variantIds to add to cart. Like to add data-variant-id to the variant element, and collect ones which are actively chosen.

var variantIds = [VARIANT_ID_1, VARIANT_ID_2]

var onSubmitQueue = function(variantIds) {
    if (variantIds.length) {     
        var variantId = variantIds.shift();
        var formElement = document.querySelector('form[action^="/cart/add"]'),
        formData = new FormData(formElement);
        formData.set('id', variantId); // re-set the variant id        
        formData.set('quantity', formData.get('quantity')); // manually set the quantity

        fetch('/cart/add.js', {
          credentials: 'same-origin',
          method: 'POST',
          headers: {
            'Accept': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
          },
          body: formData
        }).then(function (response) {
          if (response.ok) {
            console.log('add to cart successfully with variant: ', variantId);
            onSubmitQueue(variantIds);          
          } else {
            // Show error you get
          }
    } else {
      document.location.href = '/cart';
      console.log('------DONE-----')
    }
}

 

 

Published by

Colin Dao

I am a hardworking Rubyist in Hanoi, Vietnam

Leave a comment