Dedicated to the Hydrogen framework, headless commerce, and building custom storefronts using the Storefront API.
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!
Solved! Go to the solution
This is an accepted solution.
Hi @SuperBand !
Let's try the code below:
var jsonToSend = {"items": throwAwayArray};
var myJSON = JSON.stringify(jsonToSend );
This part of the code creates a JSON object jsonToSend containing "items" as a key and your array of items as its value. It is then passed to JSON.stringify() instead of throwAwayArray.
Let me know if that works for you!
This is an accepted solution.
Hi @SuperBand !
Let's try the code below:
var jsonToSend = {"items": throwAwayArray};
var myJSON = JSON.stringify(jsonToSend );
This part of the code creates a JSON object jsonToSend containing "items" as a key and your array of items as its value. It is then passed to JSON.stringify() instead of throwAwayArray.
Let me know if that works for you!
Cheers, mate! That did the trick!
According to JHK, this piece of the code makes a JSON object jsonToSend containing "things" as a key and your variety of things as its worth. It is then passed to JSON.stringify() rather than throwAwayArray.
In order to check the validity of a string whether it is a JSON string or not, We're using the JSON File. parse()method with a few variations. JSON. parse() This method parses a JSON string and constructs the JavaScript value or object specified by the string.