I’m working on a Shopify store and trying to implement an add to cart feature that doesn’t refresh the page. Currently when someone clicks add to cart, it redirects to the cart page which creates a poor user experience.
I found Shopify’s AJAX API documentation but I’m struggling with the implementation. They provide a JavaScript library with functions like:
// Function to add items to cart via AJAX
StoreAPI.insertProduct = function(product_id, qty, callback) {
var qty = qty || 1;
var options = {
method: 'POST',
endpoint: '/cart/add.js',
payload: 'quantity=' + qty + '&id=' + product_id,
format: 'json',
onSuccess: function(item_data) {
if ((typeof callback) === 'function') {
callback(item_data);
}
else {
StoreAPI.onProductAdded(item_data);
}
},
onFailure: function(request, status) {
StoreAPI.handleError(request, status);
}
};
jQuery.ajax(options);
};
And also:
// Function to add items from form data
StoreAPI.insertFromForm = function(form_element, callback) {
var options = {
method: 'POST',
endpoint: '/cart/add.js',
payload: jQuery('#' + form_element).serialize(),
format: 'json',
onSuccess: function(item_data) {
if ((typeof callback) === 'function') {
callback(item_data);
}
else {
StoreAPI.onProductAdded(item_data);
}
},
onFailure: function(request, status) {
StoreAPI.handleError(request, status);
}
};
jQuery.ajax(options);
};
I tried setting up my form like this:
<form action="/cart/add" method="post" class="product-form" id="item-form-{{ product.id }}">
<input type="submit" name="add" value="Add to Cart" class="btn-primary" onclick="return false; StoreAPI.insertProduct({{variant.id}}, 1, 'success')"/>
</form>
But nothing happens when I click the button. I also tried using the form-based approach but keep getting variant ID errors. What’s the correct way to implement this? I’ve been stuck on this for days and would really appreciate some guidance on getting AJAX cart functionality working properly.