How can i add a few products to cart with AJAX

Solved
onyxmoonstone
New Member
2 1 1

Hi everyone!

How can i add a few products to cart with AJAX?

Only first product is in the cart

function addAllItems(array){
	Shopify.queue = [];
	  var quantity = {{ cart.item_count }} ;
	  var newArray = array.split(',');
	  for (var i = 0; i < newArray.length; i++) {
	    product = newArray[i]
	    Shopify.queue.push({
	      variantId: product,
	    });
          }
	  Shopify.moveAlong = function() {
	  // If we still have requests in the queue, let's process the next one.
	  if (Shopify.queue.length) {
	    var request = Shopify.queue.shift();
	    var data = 'id='+ request.variantId + '&quantity=1'
	    $.ajax({
	      type: 'POST',
              url: '/cart/add.js',
	      dataType: 'json',
	      data: data,
	      success: function(res){
	        Shopify.moveAlong();
		  quantity += 1;
	     },
             error: function(){
	     // if it's not last one Move Along else update the cart number with the current quantity
		  if (Shopify.queue.length){
		    Shopify.moveAlong()
		  } else {
		    $('#cart-number').replaceWith("<a href="/cart" id="cart-number">View cart (" + quantity + ")</a>")
		  }
	      }
           });
        }
	 // If the queue is empty, we add 1 to cart
	else {
	  quantity += 1;
	  console.log('success');
	 }
       };
    Shopify.moveAlong();
  };
addAllItems('40591701508262,40684546424998,40684658360486')

All I have is 422 error:
POST https://get-bulk.myshopify.com/cart/add.js 422                shop_events_listener-eb19870e6f215e4e4acd8067d24ecfcbfee2d96d96aa8607e8fd45edf40eacc6.js:1 

0 Likes
onyxmoonstone
New Member
2 1 1

This is an accepted solution.

Found the solution

buyAll.addEventListener('click', async function() {

for ( let f of formsAll ) {
varId = +f.querySelector('option').value
varQty = +f.querySelector('[name="quantity"]').value

formData = {
'items': [{
'id': varId,
'quantity': varQty
}]
};

await fetch('/cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
.then(response => {
})
.catch((error) => {
console.error('Error:', error);
});

}

})