Skip to content

Instantly share code, notes, and snippets.

@jimmijazz
Last active November 10, 2022 00:06
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 jimmijazz/0932e9231b51b717c1378441db31a8bf to your computer and use it in GitHub Desktop.
Save jimmijazz/0932e9231b51b717c1378441db31a8bf to your computer and use it in GitHub Desktop.
Add to Cart with AJAX Add to Cart(Jake)
<!-- This code will add an item to the cart on button click. -->
{%- assign has_bib = false -%}
{%- assign has_jersey = false -%}
{%- assign has_bundle = false -%}
{%- for item in cart.items -%}
{% if item.product.type == 'Bib' -%}
{%- assign has_bib = true -%}
{%- elsif item.product.type == 'Jersey' -%}
{%- assign has_jersey = true -%}
{%- endif -%}
{% endfor -%}
{%- if has_bib and has_jersey -%}
{%- assign has_bundle = true -%}
{%- endif -%}
%- unless has_bundle -%}
{%- if has_bib or has_jersey -%}
{%- if has_bib -%}
{%- assign product_id = 123123123 -%} <!-- Product ID of a Jersey -->
{%- else -%}
{%- assign product_id = 12341234 -%} <!-- Product ID of a Bib -->
{%- endif -%}
{%- endunless -%}
<button id="upsell-to-cart">Add to Cart</button>
<script>
$('#upsell-to-cart').on('click',function(){
var product_id ={{ product_id }} ; // Change this to the variant ID you would like added. Or use it with the code above.
data = {
"quantity": 1,
"id": product_id
};
jQuery.ajax({
type: 'POST',
url: '/cart/add.js',
data: data,
dataType: 'json',
success: function() {
window.location.href = '/cart'; // Reload the cart to show the changes
}
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment