Created
February 1, 2021 03:54
-
-
Save dleatherman/abf685e31d0f6472f7aa2be998dc859a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Example code showing how to add an item to | |
the cart in Shopify using the Fetch API. | |
The important line is where we add the | |
X-Requested-With header. Without that the | |
fetch call will fail with a bad request error. | |
*/ | |
(function(){ | |
var addData = { | |
'id':21373873027, /* for testing, change this to a variant ID on your store */ | |
'quantity':1 | |
}; | |
fetch('/cart/add.js', { | |
body: JSON.stringify(addData), | |
credentials: 'same-origin', | |
headers: { | |
'Content-Type': 'application/json', | |
'X-Requested-With':'xmlhttprequest' /* XMLHttpRequest is ok too, it's case insensitive */ | |
}, | |
method: 'POST' | |
}).then(function(response) { | |
return response.json(); | |
}).then(function(json) { | |
/* we have JSON */ | |
console.log(json) | |
}).catch(function(err) { | |
/* uh oh, we have error. */ | |
console.error(err) | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment