Hi, we’re trying to sell an engraving service as an addon to the keychains we sell. We charge an extra amount for this so we want to we’re trying to hook into the add to cart function to add it as a Product but so far it’s not working. We’ve tried the following
- Adding functionality to the Add To Cart button
document.getElementById("AddToCart").onclick = function(event) {
fetch(window.Shopify.routes.root + 'cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
'id': {{ variant_id }},
'quantity': 1,
'properties': {
'engraving': {{ engraving }}
}
})
}).then(response => {
return response.json();
}).catch((error) => {
console.error('Error', error);
})
}
- Hooking into the theme’s Add To Cart function in theme.js.liquid
ShopifyAPI.addItemFromForm = function(form, callback, errorCallback) {
var formData = new FormData(form);
// Add to Cart call for the engraving
addEngravingToCart();
var params = {
type: 'POST',
url: '/cart/add.js',
data: formData,
processData: false,
contentType: false,
dataType: 'json',
success: function(line_item) {
if (typeof callback === 'function') {
callback(line_item, form);
} else {
ShopifyAPI.onItemAdded(line_item, form);
}
},
error: function(XMLHttpRequest, textStatus) {
if (typeof errorCallback === 'function') {
errorCallback(XMLHttpRequest, textStatus);
} else {
ShopifyAPI.onError(XMLHttpRequest, textStatus);
}
}
};
jQuery.ajax(params);
};
In both cases, we get inconsistent results and only 1 of the 3 following scenarios happen everytime we click the Add To Cart button
A) Only the Engraving Product gets added to cart
B) Only the Keychain Product get added to the cart
C) Both the Engraving Product and the Keychain Product gets added to the cart
Is there a way that we can get C to work consistently? If it helps, our theme’s Add to Cart function is below
ShopifyAPI.addItemFromForm = function(form, callback, errorCallback) {
var formData = new FormData(form);
var params = {
type: 'POST',
url: '/cart/add.js',
data: formData,
processData: false,
contentType: false,
dataType: 'json',
success: function(line_item) {
if (typeof callback === 'function') {
callback(line_item, form);
} else {
ShopifyAPI.onItemAdded(line_item, form);
}
},
error: function(XMLHttpRequest, textStatus) {
if (typeof errorCallback === 'function') {
errorCallback(XMLHttpRequest, textStatus);
} else {
ShopifyAPI.onError(XMLHttpRequest, textStatus);
}
}
};
jQuery.ajax(params);
};




