Skip to content

Instantly share code, notes, and snippets.

@hezninja
Created July 7, 2022 03:07
Show Gist options
  • Save hezninja/962974cb8dc87e5cf4cdf9dd434afa62 to your computer and use it in GitHub Desktop.
Save hezninja/962974cb8dc87e5cf4cdf9dd434afa62 to your computer and use it in GitHub Desktop.
Shopify Ajax API - Add Item to cart
<script>
var items = ['id': VARIANT_ID,'quantity': 1];
function addToCart(items){
let formData = {
'items': items
};
fetch(window.Shopify.routes.root + 'cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
.then(response => {
alert('Added Product To Cart');
return response.json();
})
.catch((error) => {
console.error('Error:', error);
});
}
</script>
<button onclick="addToCart(items)">Add to Cart</button>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment