Add multiple products to cart with one button

GSLFab
Excursionist
32 0 5

Hey guys,
So we've recently added some product bundles to the website, and I've spent most of the day looking at things that try to explain how to add multiple products to the cart from AJAX to forms, but I can not wrap my head around why it's not working. I'll show what I currently have on my store, take from this article.

<script>
data = {
  items: [
    {
      quantity: 1,
      id: 2737248338005,
      properties: {
        'MAF sensor': 'Without MAF port',
        'Colour': 'Brushed Stainless'
      }},
	{
      quantity: 1,
      id: 2712481398869,
      properties: {
        'System Type': 'DPF Back',
        'Vehicle Year Model': '2022',
        'Vehicle Type': 'Dual cab'
      }},
	{
      quantity: 1,
      id: 4600435179605,
      properties: {
        'Panel Filter': 'GSL Performance Filter (+$121.90)',
        'Colour': 'Brushed Stainless'
      }}

    ]
});
  
  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)
  });
}
</script>
<button id="add-{{ collections['Bundle1'].id }}" onclick="addAllItems('{% for product in collections['Bundle1'].products %}
	{{ product.selected_or_first_available_variant.id }}
		{% unless forloop.last %},
		{% endunless %}
	{% endfor %}'); return false;">Add to cart
</button>

 It's on this page - https://gslfab.com.au/pages/gsl-bundles
It comes up with an 'Add to cart' button (haven't styled it yet), but nothing happens when I click it. I've got the button linked from a page builder (Pagefly) and used custom html/liquid just to include a snippet I made, '{% include 'add-multiple-cart' %}' and all that code is located in the snippet.

 

Long Story Short

 

If anyone knows how to make an add to cart button, that allows me to add multiple products to cart, and select the variants similar to what's seen in the previous code (or if you have an alternate way that's easier that'll be great too), I - and I'm sure many others - would be ever greatful!

Thanks so much everyone

Replies 0 (0)