1

Have been trying to get cart updates via ajax.

I've looked at this answer: 'https://craftcms.stackexchange.com/questions/17347/update-commerce-cart-using-ajax'

My cart seem to update ok but I can't seem to get an alert to confirm it which will prevent me from adding post-submission messaging etc.

My code so far is:

HTML

<form method="POST" id="addToCartForm"  class="voucher-purchase needs-validation" novalidate >
        <input type="hidden" name="action" value="commerce/cart/update-cart">
                                <input type="hidden" name="purchasableId" value="{{ voucher.purchasableId }}">
                                {{ actionInput('commerce/cart/update-cart') }}
                                {{ csrfInput() }}

                                <input type="hidden" type="number" name="qty" value="1">
                                <div class="form-group">
                                    <label>TO:</label>
                                    <p>Please enter the name of the voucher recipient.</p>
                                    <input id="validationCustom01" class="form-control py-3" type="text" name="options[to]" placeholder="Recipient's Name" required >
                                    <div class="invalid-feedback">Please enter recipient name.</div>
                                </div>
                                <div class="form-group">
                                    <label>FROM:</label>
                                    <p>Please enter who is gifting the voucher.</p>
                                    <input class="form-control py-3"  type="text" name="options[from]" placeholder="Your Name" required > 
                                    <div class="invalid-feedback">Please enter your name.</div>
                                </div>
                                <div class="form-group">
                                    <label>MESSAGE: (Optional):</label>
                                    <p>Please enter a personalised message to the voucher recipient.</p>
                                    <textarea class="form-control py-3" rows="8" name="options[message]" placeholder="Enter your personalised message..."></textarea>
                                    <div class="invalid-feedback">Please enter a message to include with the voucher.</div>
                                </div>
                                <div class="form-group">
                                    {% if voucher.customAmount %}
                                    <label>AMOUNT:</label>
                                    <p>Please nominate the value of the voucher.</p>
                                    <div class="amount afterWrap">
                                        <input class="voucherValue form-control" required  type="number" name="options[amount]" placeholder="Amount" step="25">
                                        <div class="invalid-feedback">Please specify a value</div>
                                    </div>
                                    {% endif %}
                                </div>
                                <div class="form-group mt-5">
                                    <input type="submit" value="Add to cart" class="add-to-cart button btn btn-black">
                                    <input id="addToCart" type="submit" value="Checkout" class="button btn btn-black">
                                </div>
                            </form>

JS

   $(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!');
            }
        }
    });        
});

});

Has anyone been able to achieve update cart via ajax with something like the above?

2 Answers 2

2

Forgive me for perhaps answering a substitute question but it seems to me as though what you really need to know is how to do basic debugging in JavaScript, since it only requires a quick bit of console.log() to see why your conditional check is failing:

To debug your code, examine the response object by putting console.log(response) in your success function, and then submitting the form with your inspector's console tab open. You'll notice that, in Commerce 4 at least, the response object does not include any such property called success, only cart, message, modelName and redirect:

enter image description here

You could check the message property for the exact string "Cart updated.", but that seems a bit fragile to me (especially if your site could potentially be translated in future). There's a better way - if you force a deliberate error, you'll notice that the error response object contains some useful properties, any of which could be used in a conditional check: error, exception and status. So for example you could check whether response.error is empty. Equally, you could check for the absence of the cart object.

1
  • Got me on the right track - thank you! Commented Oct 31, 2023 at 0:43
2

The behaviour with ajax responses changed significantly with Craft 4 / Commerce 4 - I have updated my answer to that original question: Update Commerce Cart using Ajax

...to cover both scenarios.

1
  • Awesome - thank you!! Commented Oct 31, 2023 at 0:43

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.