Skip to content

Instantly share code, notes, and snippets.

@joshuaiz
Last active June 21, 2023 18:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshuaiz/f61ef7c43d7bae02a7f323d45af599d6 to your computer and use it in GitHub Desktop.
Save joshuaiz/f61ef7c43d7bae02a7f323d45af599d6 to your computer and use it in GitHub Desktop.
Shopify Add To Cart with options
const handleAddToCart = (e) => {
e.preventDefault()
if (
productOptions.embroidery === true &&
productOptions.embroiderySubmitted === false
) {
setEmbroideryError(true)
alert(
'Please select all required embroidery options and submit before adding to your cart.'
)
return
} else {
setEmbroideryError(false)
}
// if we don't have an embroidered product, bail
if (productOptions.embroidery === false) {
return
}
// get the variantId of the product we are embroidering
let variantId = document.getElementById('variant-id').value
variantId = parseInt(variantId)
// console.log('variantId', variantId)
// prepare data for Shopify
let formData = {
items: [
{
id: 39726235418686,
quantity: 1,
properties: {
variantId: variantId,
SKU: 'embroidery',
},
},
{
id: variantId,
quantity: quantity,
properties: {
'Add Embroidery?':
productOptions.embroidery === true ? '✓ Yes' : '',
Type:
productOptions.embroideryType.monogram === true
? 'Monogram'
: productOptions.embroideryType.text === true
? 'Text'
: productOptions.embroideryType.mama === true
? 'Mama'
: 'Single',
Text:
productOptions.embroideryText !== ''
? productOptions.embroideryText
: '',
'Web Font': productOptions.embroideryFont
? productOptions.embroideryFont.webName
: '',
'Font Name': productOptions.embroideryFont
? productOptions.embroideryFont.fontName
: '',
'Thread Color': productOptions.embroideryColor
? productOptions.embroideryColor.threadColor
: '',
'Color': productOptions.embroideryColor
? productOptions.embroideryColor.name
: '',
'Embroidery Price':
'$' + productOptions.embroideryPrice.toFixed(2),
},
},
],
}
fetch(window.Shopify.routes.root + 'cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
})
.then((response) => {
console.log('response from cart/add', response)
clearOptions()
setTimeout(() => {
document.getElementById('open-cart-drawer').click()
}, 500)
return response.json()
})
.catch((error) => {
console.error('Error:', error)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment