Hi Folks. I’m writing some javascript to add multiple items to the cart. The problem I’m having is that cart.js is complaining that my JSON is invalid some how. (cart is sending back a 400)
Here’s a valid JSON string that uses read variant ID’s: [{“id”:“13596169994330”,“quantity”:1},{“id”:“13596169994330”,“quantity”:1},{“id”:“13596169994330”,“quantity”:1}]
What I noticed is that on the API documentation for Ajax cart, https://shopify.dev/api/ajax/reference/cart , the json examples you provide always have an ‘items’ element for the json.
If I hard code a JSON object with that ‘items’ element, it’ll add all of the items to the cart without issue but I cannot for the life of me figure out how to add that ‘items’ element to my javascript object which is then passed through JSON.stringify(); I’ve been trying to figure this out for a few days now and figured maybe I’d get lucky with support.
Here’s my code sample:
(the object received by the function is a simple array with variant ID’s and I hard code the quantity as 1. All vars not called within the function are defined globally outside of the function)
function addBadgesToCart(obj) {
for(var i = 0; i < obj.length; i++) {
newJsObj.id = obj[i];
newJsObj.quantity = 1;
throwAwayArray.push(newJsObj)
}
var myJSON = JSON.stringify(throwAwayArray);
var xhr = new XMLHttpRequest();
xhr.open(“POST”, ‘/cart/add.js’, true);
xhr.setRequestHeader(‘Content-Type’, ‘application/json; charset=UTF-8’);
xhr.send(myJSON);
}
Appreciate any help!