Liquid, JavaScript, themes, sales channels
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);
};
});
});
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.
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,
},
]
Portrait of Stephen positioned next to an image of planet Earth, with the Stephen's World ...
By JasonH Mar 18, 2024Digital marketers and app developers have tracked activity in apps and websites for yea...
By Ollie Mar 13, 2024February was an exciting month with Shopify Editions, informative webinars, and more! F...
By JasonH Mar 7, 2024