Shopify Asynchronous Ajax Add To Cart - Working Partially?
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/page
Solution 1:
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.
Solution 2:
var length = {{ product.variants.size }};
$(document).ready(function () {
$("#quantity-0").focus();
$("#submit-table").click(function(e) {
e.preventDefault();
//array for Variant Titlesvar toAdd = newArray();
var qty ;
for(i=0; i < length; i++){
toAdd.push({
variant_id: $("#variant-"+i).val(),
quantity_id: $("#quantity-"+i).val() || 0
});
}
functionmoveAlong(){
if (toAdd.length) {
var request = toAdd.shift();
var tempId= request.variant_id;
var tempQty = request.quantity_id;
var params = {
type: 'POST',
url: '/cart/add.js',
data: 'quantity='+tempQty+'&id='+tempId,
dataType: 'json',
success: function(line_item) {
alert("Product Added to Cart");
moveAlong();
},
error: function() {
//console.log("fail");moveAlong();
}
};
$.ajax(params);
}
else {
document.location.href = '/cart';
}
};
moveAlong();
});
});
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><formclass="page-width"><table><tr><th>Name</th><th>Quantity</th><th>Stock</th></tr>
{% for variant in product.variants %}
<tr><td>{{ variant.title }} - {{ variant.price | money }}</td><td><inputtype="hidden"value="{{ variant.id }}"id="variant-{{ forloop.index0 }}"/><inputtype="number"value="0"id="quantity-{{ forloop.index0 }}"/></td><td>{{ variant.inventory_quantity }} in stock.</td></tr>
{% endfor %}
</table><divclass="purchase-section{% if product.variants.size > 1 %} multiple{% endif %}"><divclass="purchase">
{% unless product.available %}
<p>Sold Out</p>
{% else %}
<br /><inputtype="submit"value="Add!"class="btn"id="submit-table"/>
{% endunless %}<inputtype="reset"class="btn"value="Reset"></div></div></form></div><scripttype="text/javascript"charset="utf-8">
//<![CDATA[
// Including jQuery conditionally.
if (typeof jQuery === 'undefined') {
document.write({{ "http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" | script_tag | json }});
document.write('<script type="text/javascript">jQuery.noConflict();<\/script>');
}
//]]>
</script>
Post a Comment for "Shopify Asynchronous Ajax Add To Cart - Working Partially?"