1 button add to cart for 2 products

fabriziom
Tourist
7 1 1

Hi community,

I coded a button "bundle add to cart" to add 2 products (of bundle) in the cart, but it doesn't work! It added only 1 product to the cart! but the console shows me 2 calls!

this is the HTML in the cart drawer:

// for every bundle product
<input type="hidden" class="cross-check" value="{{ variant.id }}">


//out of the loop
<button id="csbundle-button" class="js-AddToCart" onclick="addItemtoCart()">ADD BUNDLE</button>

and this is the JS:

$('#csbundle-button').click(function(addItemtoCart) {
  $.each($('.cross-check'),function(i,v){
  var id = $(this).val();
  let addData = {
      'id': id,
      'quantity': 1
    };

    fetch('/cart/add.js', {
      method: 'POST',
      credentials: 'same-origin',
      headers: {
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest'
      },
      body: JSON.stringify(addData)
    }).then(function (data) {
      if (data.status == 200) {
        window.location.refresh;
        return
      }
      else {
        console.log('Request returned an error', data)
      };
    })
    .catch(function (error) {
      console.log('Request failed', error);
    });
  window.onerror = function(message, file, line) {
  console.log('An error occured at line ' + line + ' of ' + file + ': ' + message);
};
});
});

 

Replies 3 (3)

Jason
Shopify Expert
11190 225 2282

On quick glance of your code it appears as if you could be making multiple calls to the ajax API at once. If you are choosing to add one at a time you must wait for the first to be added, before adding the next. Sending multiple calls at once without waiting will result in missed calls/errors.

★ I jump on these forums in my free time to help and share some insights. Not looking to be hired, and not looking for work. http://freakdesign.com.au ★
fabriziom
Tourist
7 1 1

Hi Jason,

Thank you for your reply, i want to add both items together. How i could do this?

thanks

Jason
Shopify Expert
11190 225 2282

When you post to the add endpoint it can accept an array of items.
So you could look to pass something like this, for two items at once.

  items: [
    {
      quantity: 1,
      id: 123456789,
    },
    {
      quantity: 1,
      id: 987654321,
    },
  ]

  

★ I jump on these forums in my free time to help and share some insights. Not looking to be hired, and not looking for work. http://freakdesign.com.au ★