I currently have a 'Add to Cart' button which submits product data from an array and posts the data using AJAX.
Currently on submit only one of the three products are been send to the cart.
I was told to use .then function after each AJAX post but I'm unsure how to tie this in with the for() function and the array.
Any and all help would be very much appreciated! Thank you.
function addtocart() {
var products = [{
'id': 32,
'qty': 2
}, {
'id': 33,
'qty': 1
}, {
'id': 34,
'qty': 5
}];
$('.submit').on('click', function(e) {
e.preventDefault();
for (var j = 0; j < products.length; j++) {
jQuery.ajax({
type: 'POST',
url: 'XXX/?post_type=product&add-to-cart=' + products[j].id + '&quantity=' + products[j].qty
});
}
});
}
<div class="addtocart">
<button class="submit">Add to Cart</button>
</div>
Update:
function addtocart() {
var products = [{'product_id':32,'quantity':2},{'product_id':33,'quantity':1},{'product_id':34,'quantity':5}];
$('.submit').on('click', function(e){
e.preventDefault();
$.ajax(
{
type:'POST',
url:'XXX/?post_type=product&add-to-cart',
data:JSON.stringify(products)
}
);
console.log(JSON.stringify(products));
});
}
addtocart();
Network Snapshot
Console Log Snapshot
I was told to do something like this, but I can't add an ID without it been within a for()
url: 'XXX/?post_type=product&add-to-cart='+IDHERE