<p>Yes, you can do all the normal commerce actions via ajax.</p>
<p>How this is done changed slightly with Craft 4/Commerce 4, so use the appropriate approach below.  (Basically, they used to use an attribute on the response (<code>response.success</code>) - but now the use response codes instead to determine success/failure).</p>
<p>A basic recipe is this...</p>
<p>HTML:</p>
<pre><code>        &lt;form method=&quot;POST&quot; id=&quot;addToCartForm&quot;&gt;
        {{ getCsrfInput() }}
        &lt;input type=&quot;hidden&quot; name=&quot;action&quot; value=&quot;commerce/cart/updateCart&quot;&gt;
        &lt;input type=&quot;hidden&quot; name=&quot;redirect&quot; value=&quot;/cart&quot;&gt;
        &lt;input type=&quot;hidden&quot; name=&quot;purchasableId&quot; value=&quot;{{ product.id }}&quot;&gt;
        &lt;input type=&quot;number&quot; name=&quot;qty&quot;&gt;
        &lt;/form&gt;
</code></pre>
<p>JS (Craft/Commerce 4, and presumably later...):</p>
<pre><code>        $form = (&quot;#addToCartForm&quot;);
        var form_data = $form.serializeArray()
        form_data.push({
            name: window.csrfTokenName,
            value: window.csrfTokenValue
        })

        $.ajax({
            type: 'post',
            url: action,
            dataType: &quot;json&quot;,
            data: formData,

            success: function (response, textStatus, jqXHR) {                  
                if (jqXHR.status === 200){
                     // Handle success...
                }
            },
            error: function(request, status, error) {
                // Handle failure
            }
</code></pre>
<p>JS (up to Craft/Commerce 3):</p>
<pre><code>        $form = (&quot;#addToCartForm&quot;);
        var form_data = $form.serializeArray()
        form_data.push({
            name: window.csrfTokenName,
            value: window.csrfTokenValue
        })

        $.ajax({
            type: 'post',
            url: '/',
            data: form_data,
            success: function(response) {
                if (response.success) {
                    // handle success
                }
                else {
                    // handle failure
                }
            }
</code></pre>
<p>....response.cart will have the updated cart in it.</p>

CC BY-SA 4.0
2016-10-20T05:12:20.777Z
2023-10-29T23:45:53.183Z
2023-10-29T23:45:53.183Z
Jeremy Daalder
<p>Is there a way to update the cart using ajax?</p>

<p>I've tried something like:</p>

<pre><code>$('span.quick-cart-add&gt;p&gt;a').click(function(e){

    e.preventDefault();

    var data                    = {};
    data["purchasableId"]       = $(this).data("id");
    data["qty"]                 = $(this).data("qty");
    data[window.csrfTokenName]  = window.csrfTokenValue;


    $.post( "/actions/commerce/cart/updateCart", data, function(response) {

        alert( "success" );

    }).always(function(response) { console.log(data, response); });

});
</code></pre>

<p>I've tried passing <code>"lineItemId"</code> instead of <code>"purchasableId"</code>, and also sending to <code>"/actions/commerce/cart/updateLineItem"</code>, they all return <code>response.success</code> but the cart is never actually updated.</p>

<p>Am I not sending the right amount of fields/values, or is there something I'm missing when trying to accomplish this via ajax?</p>

CC BY-SA 4.0
2023-10-23T12:22:08.043Z
I'm trying to implement the above but not getting a response. My cart seems to updating ok via ajax, but I'd like the 'Success' message to execute so I can build out the next part of the script. $(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("Success"); } else { alert("Failure!"); } } });
DieselHashtag
<plugin-craftcommerce><ajax><javascript>
Update Commerce Cart using Ajax
# Update Commerce Cart using Ajax

(Asked by: username_0 on 2016-10-19)

Is there a way to update the cart using ajax?
I've tried something like:
$('span.quick-cart-add>p>a').click(function(e){

    e.preventDefault();

    var data                    = {};
    data["purchasableId"]       = $(this).data("id");
    data["qty"]                 = $(this).data("qty");
    data[window.csrfTokenName]  = window.csrfTokenValue;


    $.post( "/actions/commerce/cart/updateCart", data, function(response) {

        alert( "success" );

    }).always(function(response) { console.log(data, response); });

});

I've tried passing "lineItemId" instead of "purchasableId", and also sending to "/actions/commerce/cart/updateLineItem", they all return response.success but the cart is never actually updated.
Am I not sending the right amount of fields/values, or is there something I'm missing when trying to accomplish this via ajax?

**Tags:** plugin-craftcommerce, ajax, javascript
> **Comments:**
> **username_1**: I'm trying to implement the above but not getting a response. My cart seems to updating ok via ajax, but I'd like the 'Success' message to execute so I can build out the next part of the script. $(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("Success"); } else { alert("Failure!"); } } });  

---

## 1 answers

### Answer by username_2 on 2016-10-20. Score: 8 | Accepted answer

Yes, you can do all the normal commerce actions via ajax.
How this is done changed slightly with Craft 4/Commerce 4, so use the appropriate approach below.  (Basically, they used to use an attribute on the response (response.success) - but now the use response codes instead to determine success/failure).
A basic recipe is this...
HTML:
        
        {{ getCsrfInput() }}
        
        
        
        
        

JS (Craft/Commerce 4, and presumably later...):
        $form = ("#addToCartForm");
        var form_data = $form.serializeArray()
        form_data.push({
            name: window.csrfTokenName,
            value: window.csrfTokenValue
        })

        $.ajax({
            type: 'post',
            url: action,
            dataType: "json",
            data: formData,

            success: function (response, textStatus, jqXHR) {                  
                if (jqXHR.status === 200){
                     // Handle success...
                }
            },
            error: function(request, status, error) {
                // Handle failure
            }

JS (up to Craft/Commerce 3):
        $form = ("#addToCartForm");
        var form_data = $form.serializeArray()
        form_data.push({
            name: window.csrfTokenName,
            value: window.csrfTokenValue
        })

        $.ajax({
            type: 'post',
            url: '/',
            data: form_data,
            success: function(response) {
                if (response.success) {
                    // handle success
                }
                else {
                    // handle failure
                }
            }

....response.cart will have the updated cart in it.


---

