I am building a special Shopify page, where multiple items can be added to the cart via Shopify’s Ajax API. I set up a test version of the page here: https://monstermuffin.com/pages/ajax-test
Here is the js code I have currently to set up the asynchronous call / add to cart:
Shopify.queue = [];
Shopify.moveAlong = function() {
if (Shopify.queue.length) {
var request = Shopify.queue.shift();
Shopify.addItem(request.variantId, request.quantity, request.properties, Shopify.moveAlong);
}
else {
//document.location.href = '/cart';
}
};
Shopify.addItem = function(id, qty, properties, callback) {
var params = {
quantity: qty,
id: id,
properties: properties
};
$.ajax({
type: 'POST',
url: '/cart/add.js',
dataType: 'json',
data: params,
success: function(){
if(typeof callback === 'function'){
callback();
}
},
error: function(){
}
});
}
function push_to_queue(variantID, quantity, properties,callback) {
Shopify.queue.push({
variantId: variantID,
quantity: quantity,
properties: properties
});
if(typeof callback === 'function'){
callback();
}
}
$('#add-helmet-panties').click(function() {
$('.quantity-field:visible').each(function() {
var thisVariant = $(this).prop('id');
var thisQuantity = parseInt($(this).val(), 10) || 0;
var theseProps = {
'Base Colour': $('#base-colour').val()
}
push_to_queue(thisVariant, thisQuantity, theseProps, Shopify.moveAlong);
});
});
Oddly, it is currently adding only 3 or 4 of the products to the cart at a time.
I’ve really struggled with this! Any advice would be appreciated. I can provide more information if needed!
2
Answers
It is simple… you want your click listener to simply iterate the NON-ZERO variants, and add them to the queue. So call push_to-queue. Do not bother with the call to move along. Instead, once the queue is all filled, then you call move along.
It is funny, I wrote the pseudo-code for this originally, and Caro at Shopify re-wrote it into this version, now public for almost ten years… neat.
Also it seems your concept of the base colour property is off? It is being applied to all the variants. Why bother? Instead, set it as a cart attribute where the product has a base colour, once. More efficient. Makes more sense.