2

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

});

1 Answer 1

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!

8
  • 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: dropbox.com/s/as8okaskioduv0i/…
    – Stephen
    Commented Mar 10, 2017 at 0:43
  • Should be fixed Commented Mar 10, 2017 at 0:50
  • (changed above) Commented Mar 10, 2017 at 0:50
  • 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: dropbox.com/s/clzqw5a8kad5yb6/…
    – Stephen
    Commented Mar 10, 2017 at 1:17
  • Sounds like a jquery not being included/wrong version issut to me - you want 1.7+ according to: api.jquery.com/on Commented Mar 11, 2017 at 0:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.