5

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?

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!"); } } }); Oct 23 at 12:22

1 Answer 1

8

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:

        <form method="POST" id="addToCartForm">
        {{ getCsrfInput() }}
        <input type="hidden" name="action" value="commerce/cart/updateCart">
        <input type="hidden" name="redirect" value="/cart">
        <input type="hidden" name="purchasableId" value="{{ product.id }}">
        <input type="number" name="qty">
        </form>

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.

Your Answer

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

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