Why does my 'add to cart' button only add one product instead of two?

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

//out of the loop

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);
};
});
});

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.

1 Like

Hi Jason,

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

thanks

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,
    },
  ]