How do I replace the items syntax content of a JQuery.post request with a variable?

Tourist
14 0 1
I'm trying to write a jQuery.post request that adds items to the cart at the click of a button.  I am successful at doing so but want the contents of the post request to have the contents in the form of a JS variable instead of hardcoded.
 

An example of before working in my system.

 

<a id="someLink" onclick="builder()"><input type="submit"
                    value="Click me" /></a>

<script>
function builder() {
       jQuery.post('/cart/add.js', {
                    items: [
                        {
                            quantity: 1,
                            id: 15551948062829
                        }
                        ,{
                            quantity: 1,
                            id: 30588859482221
                        }
                    ]
                });
}
document.getElementById('someLink').href = "/cart";

</script>

What I am trying to do is have the whole contents of items and everything within {items[...} syntax be in a JS variable instead that I can later call there.

 

A non-working example of how I'm trying to accomplish would look something like this:

 

 

<a id="someLink" onclick="builder()"><input type="submit"
                    value="Click me" /></a>

<script>
function builder() {

       var cartContents = " {items: [{ quantity: 1, id: 15551948062829 } , { quantity: 1, id: 30588859482221 } ] }";
       jQuery.post('/cart/add.js', cartContents);
}
document.getElementById('someLink').href = "/cart";
</script>
When I execute the latter code, nothing gets added to my cart like my first code does. Any insight would be much appreciated.

 

0 Likes