Skip to content

Instantly share code, notes, and snippets.

@JamieS
Forked from resistorsoftware/API cart attributes
Created March 2, 2011 23:30
Show Gist options
  • Save JamieS/851998 to your computer and use it in GitHub Desktop.
Save JamieS/851998 to your computer and use it in GitHub Desktop.
// ---------------------------------------------------------
// POST to cart/update.js returns the cart in JSON.
// To clear a particular attribute, set its value to an empty string.
// Receives attributes as a hash or array. Look at comments below.
// ---------------------------------------------------------
Shopify.updateCartAttributes = function(attributes, callback) {
var data = '';
// If attributes is an array of the form:
// [ { key: 'my key', value: 'my value' }, ... ]
if (jQuery.isArray(attributes)) {
jQuery.each(attributes, function(indexInArray, valueOfElement) {
var key = attributeToString(valueOfElement.key);
if (key !== '') {
data += 'attributes[' + key + ']=' + attributeToString(valueOfElement.value) + '&';
}
});
}
// If attributes is a hash of the form:
// { 'my key' : 'my value', ... }
else if ((typeof attributes === 'object') && attributes !== null) {
jQuery.each(attributes, function(key, value) {
data += 'attributes[' + attributeToString(key) + ']=' + attributeToString(value) + '&';
});
}
var params = {
type: 'POST',
url: '/cart/update.js',
data: data,
dataType: 'json',
success: function(cart) {
if ((typeof callback) === 'function') {
callback(cart);
}
else {
Shopify.onCartUpdate(cart);
}
},
error: function(XMLHttpRequest, textStatus) {
Shopify.onError(XMLHttpRequest, textStatus);
}
};
jQuery.ajax(params);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment