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?