<p>The question you link to - that is a working example really except you a) might not need the CSRF stuff if you haven't turned on CSRF protection (you should, though) - and of course the <code>...</code> at the end means you should at least finish off the function and do some error handling. </p>

<p>In any case, in this specific case, you should just in essence need:</p>

<pre><code>$(function() {

    $form = $("#addToCartForm");

    // handle submits via ajax

    $form.on('submit', function(e) {

        //Prevent the default submission
        e.preventDefault();

        //Get the form data
        var form_data = $form.serializeArray();

        // ajax it over to the server
        $.ajax({
            type: 'post',
            url: '/',
            data: form_data,
            success: function(response) {
                if (response.success) {
                    alert(response.cart);
                }
                else {
                    alert("Failure!");
                }
            }
        });        
    });

});
</code></pre>

<p>..although I am doing this on my phone.  So if you get syntax errors let me know!</p>

CC BY-SA 3.0
2017-03-10T00:43:28.123Z
Hi Jeremy, thanks for this. I got this syntax error with the above code - it's probably something I'm doing wrong or something really simple to fix! "Uncaught SyntaxError: Unexpected token )" Screenshot: https://www.dropbox.com/s/as8okaskioduv0i/Screenshot%202017-03-10%2000.40.04.png?dl=0
Stephen
CC BY-SA 3.0
2017-03-10T00:50:18.453Z
Should be fixed
Jeremy Daalder
CC BY-SA 3.0
2017-03-10T00:50:56.433Z
(changed above)
Jeremy Daalder
CC BY-SA 3.0
2017-03-10T01:17:33.010Z
Thanks Jeremy. The updated code got me past that previous error, but it's brought up a new one. Any ideas about this one? "Uncaught TypeError: $form.on is not a function" Screenshot: https://www.dropbox.com/s/clzqw5a8kad5yb6/Screenshot%202017-03-10%2001.15.58.png?dl=0
Stephen
CC BY-SA 3.0
2017-03-11T00:27:06.117Z
Sounds like a jquery not being included/wrong version issut to me - you want 1.7+ according to: http://api.jquery.com/on/
Jeremy Daalder
CC BY-SA 3.0
2017-03-11T01:03:46.097Z
Not sure what's happening, but I'm using jQuery 1.12.4 so that version should be fine, and the jQuery is definitely being loaded okay as other things work fine (jQuery Validate, Fancybox, etc).
Stephen
CC BY-SA 3.0
2017-03-11T01:17:01.640Z
`¯\_(ツ)_/¯` Well the above is definitely the essence of it - perhaps in this context jquery is not loading...it really depends on how you're structuring and building all your JS.
Jeremy Daalder
CC BY-SA 3.0
2017-03-22T23:40:45.087Z
As so there you go - phone coding is tough - I missed the second `$` on `$form = $("#addToCartForm");` apparently - sorry!
Jeremy Daalder
CC BY-SA 3.0
2017-03-09T23:22:32.773Z
2017-03-22T18:41:56.553Z
2017-03-22T18:41:56.553Z
Jeremy Daalder
<p>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.</p>

<p>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 <a href="https://craftcms.stackexchange.com/questions/17347/update-commerce-cart-using-ajax">similar question</a> 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.</p>

<p>Here's what I'm using to show how many items have been added to the cart in the header:</p>

<pre><code>{% set cart = craft.commerce.cart %}
&lt;a href="/basket"&gt;({{ cart.lineItems|length }}) Items&lt;/a&gt;
</code></pre>

<p>Here's the markup I'm using for the current non-AJAX add to cart form:</p>

<pre><code>{% for product in products %}

  {% for purchasable in product.variants %}

    &lt;form method="POST" id="addToCartForm"&gt;

      &lt;input type="hidden" name="action" value="commerce/cart/updateCart"&gt;
      &lt;input type="hidden" name="redirect" value="basket"&gt;
      &lt;input type="hidden" name="purchasableId" value="{{ purchasable.purchasableId }}"&gt;
      {{ getCsrfInput() }}

      &lt;h2&gt;{{ product.title }}&lt;/h2&gt;
      &lt;p&gt;{{ purchasable.price|commerceCurrency(cart.currency) }}&lt;/p&gt;
      &lt;input name="qty" type="number" min="1" value="1"&gt;

      &lt;input type="submit" value="Add to Cart" /&gt;

    &lt;/form&gt;

  {% endfor %}

{% endfor %}
</code></pre>

<p>Here's my functions.JS file (i.e. empty after getting nowhere with other examples that I was trying to cobble together):</p>

<pre><code>$(function() {

});
</code></pre>

<plugin-craftcommerce><ajax><jquery>
Complete working example for adding Craft Commerce items to the cart using AJAX and jQuery?
# Complete working example for adding Craft Commerce items to the cart using AJAX and jQuery?

(Asked by: username_0 on 2017-03-09)

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 %}
({{ cart.lineItems|length }}) Items

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 %}

    

      
      
      
      {{ getCsrfInput() }}

      {{ product.title }}
      {{ purchasable.price|commerceCurrency(cart.currency) }}
      

      

    

  {% 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() {

});

**Tags:** plugin-craftcommerce, ajax, jquery


---

## 1 answers

### Answer by username_1 on 2017-03-09. Score: 2

The question you link to - that is a working example really except you a) might not need the CSRF stuff if you haven't turned on CSRF protection (you should, though) - and of course the ... at the end means you should at least finish off the function and do some error handling. 
In any case, in this specific case, you should just in essence need:
$(function() {

    $form = $("#addToCartForm");

    // handle submits via ajax

    $form.on('submit', function(e) {

        //Prevent the default submission
        e.preventDefault();

        //Get the form data
        var form_data = $form.serializeArray();

        // ajax it over to the server
        $.ajax({
            type: 'post',
            url: '/',
            data: form_data,
            success: function(response) {
                if (response.success) {
                    alert(response.cart);
                }
                else {
                    alert("Failure!");
                }
            }
        });        
    });

});

..although I am doing this on my phone.  So if you get syntax errors let me know!

> **Comments:**
> **username_0**: Hi Jeremy, thanks for this. I got this syntax error with the above code - it's probably something I'm doing wrong or something really simple to fix! "Uncaught SyntaxError: Unexpected token )" Screenshot: https://www.dropbox.com/s/as8okaskioduv0i/Screenshot%202017-03-10%2000.40.04.png?dl=0  
> **username_1**: Should be fixed  
> **username_1**: (changed above)  
> **username_0**: Thanks Jeremy. The updated code got me past that previous error, but it's brought up a new one. Any ideas about this one? "Uncaught TypeError: $form.on is not a function" Screenshot: https://www.dropbox.com/s/clzqw5a8kad5yb6/Screenshot%202017-03-10%2001.15.58.png?dl=0  
> **username_1**: Sounds like a jquery not being included/wrong version issut to me - you want 1.7+ according to: http://api.jquery.com/on/  
> **username_0**: Not sure what's happening, but I'm using jQuery 1.12.4 so that version should be fine, and the jQuery is definitely being loaded okay as other things work fine (jQuery Validate, Fancybox, etc).  
> **username_1**: `¯\_(ツ)_/¯` Well the above is definitely the essence of it - perhaps in this context jquery is not loading...it really depends on how you're structuring and building all your JS.  
> **username_1**: As so there you go - phone coding is tough - I missed the second `$` on `$form = $("#addToCartForm");` apparently - sorry!  

---

