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?

7

Yes, you can do all the normal commerce actions via ajax.

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:

        $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) {
                    alert(response.cart)
                }
            ...etc

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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