Created
January 30, 2015 18:29
-
-
Save DanWebb/bb39e82483451ff167db to your computer and use it in GitHub Desktop.
Shopify only allows us to make a single call at a time adding one item at a time. Here's a method to add multiple items to the cart at once which works around that.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// add multiple items to the cart by passing an array of item objects | |
function addItems(items, callback) { | |
if(!items.length) { | |
// we ran out of items | |
if(typeof callback === 'function') callback(); | |
return; | |
} | |
$.ajax('/cart/add.js', { | |
type:'POST', | |
dataType: 'json', | |
data: items[0] | |
}) | |
.done(function(data) { | |
// remove the item we just added from the array | |
items = items.slice(1); | |
// recursively call the method passing the updated items array | |
addItems(items, callback) | |
}) | |
.fail(function(a,b,c) { | |
alert('error'); | |
console.log(a);console.log(b);console.log(c); | |
}); | |
} | |
// example usage | |
var items = [ | |
{ | |
id: 1056086132, | |
quantity: 1, | |
properties: { | |
chris: 'needs to get a life >:[' | |
} | |
}, | |
{ | |
id: 1901920231, | |
quantity: 2 | |
} | |
]; | |
addItems(items, function() { | |
alert('done'); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment