I'm using Craft Commerce and every time I click the Add to Cart button for a product, I'm redirected to the Cart page. This works okay, but I'd like to use AJAX (with jQuery v1.12.4) for this to save being redirected to the Cart page.
I'm not great with JS though, so I was trying to find a complete working example for this in the demo templates get me started but I couldn't find one. I did find a similar question on here, but I don't think that's a complete working example as when I tried putting the JS from that example in my own functions.js file, I was getting a syntax error, so this is why I'm asking my own question. Thanks in advance for any help.
Here's what I'm using to show how many items have been added to the cart in the header:
{% set cart = craft.commerce.cart %}
<a href="/basket">({{ cart.lineItems|length }}) Items</a>
Here's the markup I'm using for the current non-AJAX add to cart form:
{% for product in products %}
{% for purchasable in product.variants %}
<form method="POST" id="addToCartForm">
<input type="hidden" name="action" value="commerce/cart/updateCart">
<input type="hidden" name="redirect" value="basket">
<input type="hidden" name="purchasableId" value="{{ purchasable.purchasableId }}">
{{ getCsrfInput() }}
<h2>{{ product.title }}</h2>
<p>{{ purchasable.price|commerceCurrency(cart.currency) }}</p>
<input name="qty" type="number" min="1" value="1">
<input type="submit" value="Add to Cart" />
</form>
{% endfor %}
{% endfor %}
Here's my functions.JS file (i.e. empty after getting nowhere with other examples that I was trying to cobble together):
$(function() {
});