I’m creating a way to add all the products in a Shopify collection to the cart as a way to sell bundles.
I have a JavaScript script that determines which level of kit is selected, and loops through each product in the collection. A few products in the bundle we want added more than once, and these are controlled by the tag basicbundleqty:x. So the code loops through the tags for each product, checks for this tag, and if it has it then the qty is set to the suffix of the tag.
<script>
var selected = "not selected";
function kitSelect(){
selected = document.getElementById('select').value;
/*if(selected == "not selected"){
alert('Please select a kit level');
}
if(selected == "basic"){
alert('basic');
}
if(selected == "standard"){
alert('standard');
}
if(selected == "pro"){
alert('pro');
}*/
}
function addBundle(){
var qty = 0;
if(selected == "basic"){
{% for kitproduct in collections['Basic-Fixture-Plate-Starter-Kit'].products %}
qty = 1;
{% for t in kitproduct.tags %}
{% if t contains 'basicqty:' %}
{% assign qty = t | remove: 'basicqty:'%}
{% assign qty = qty | plus: 0 %}
qty = {{ qty | json }};
{% endif %}
{% endfor %}
jQuery.post('/cart/add.js', {
quantity: qty,
id: {{ kitproduct.variants[0].id }},
properties: {
}
});
alert(qty);
{% endfor %}
} else {
alert("Please select a kit level first");
}
window.location.reload(false);
}
</script>
This method does work, with one quirk. without the line alert(qty);
at the end of the for loop, the code does not work. If that alert is not there, the code will seemingly randomly add just one or two of the collection products.
Why does this only work with the alert()
function, and is there a fix that will allow this to add them all to cart with one click and not require the user clicking through each alert window?
2
Answers
Here's the solution. As frieder pointed out, instead of creating a request for each product in the collection I needed to create a single request and loop through each product inside the request. Here's the working function (minus the quantity check, which I need to add back in):
The problem lies within the asynchronous requests you are sending.
The loop with the alert works because the script stops every time the alert shows up. In the meantime the asynchronous request gets processed.
Shopify explicitly advises against a pattern of adding products in parallel as you can read here.
If you want to add multiple products at once you can add them using one request as described in the shopify documentation: