Reputation: 2370
I have a cookie on my Shopify site that stores variant IDs that will be added to the cart on page load:
var mmuUserCart = [
'10672503748',
'10672622148'
];
$.cookie('mmu-cart', mmuUserCart, {expires: 10});
function readCookie(handle) {
var cookieData = $.cookie(handle);
cookieData = cookieData.split(',');
if (cookieData) {
if (cookieData.length > 0) {
for (i = 0; i < cookieData.length; i++) {
console.log(cookieData[i]);
jQuery.post('/cart/add.js', {
quantity: 1,
id: cookieData[i]
});
// .fail( function(xhr, textStatus, errorThrown) {
// console.log(textStatus);
// });
}
}
}
}
$(document).ready(function() {
readCookie('mmu-cart');
});
But it only posts one of the items (randomly) and sometimes it posts both. But that's a 1/20 chance it adds both to the cart. No error message. Both items have plenty of stock. Is there a post
limit on Shopify?
Upvotes: 0
Views: 79
Reputation: 15412
jQuery.post is asynch so you need to wait for the first post to return before posting the next variant. e.g.:
var mmuUserCart = [
'10672503748',
'10672622148'
];
$.cookie('mmu-cart', mmuUserCart, {expires: 10});
function readCookie(handle) {
var cookieData = $.cookie(handle);
cookieData = cookieData.split(',');
if (cookieData) {
function postVariant(){
if(!cookieData.length) {
//update any displayed cart ?;
return;
}
var variantId = cookieData.shift();
console.log(variantId);
$.post('/cart/add.js', {
quantity: 1,
id: variantId
}).done(postVariant);
}
postVariant();
}
}
$(document).ready(function() {
readCookie('mmu-cart');
});
Upvotes: 1