BLOG

Ajax Single/ First variant add to cart button without page load Shopify

{%- assign current_variant = product.selected_or_first_available_variant -%}
<span id="color"></span>
<button
id="color"
type="button"
{% unless current_variant.available %}
disabled="disabled"
{% endunless %}
onclick="add_to_cart_grid({{current_variant.id}}, 1)"
class="btn btn--full"
>
{% if current_variant.available %}
Add to Cart
{% else %}
Out of Stock
{% endif %}
</button>

<script>
function add_to_cart_grid(variantid,qty){
var id = variantid;
var q = qty;
var ajax = {
type: "POST",
url: "/cart/add.js",
data: "quantity=" + q + "&id=" + id,
dataType: "json",
success: function (n) {
var cart = new theme.CartDrawer
cart.init()
cart.open();
},
error: function (n, c) {
console.log('fail');
}
};
jQuery.ajax(ajax)
}
</script>

Share:

Post a Comment!