0

I want to display messages on the cart page. I have made a custom module so that the shopping cart will automatically reload when the qty changes using AJAX.

Here is my js code:

define([
'jquery',
'Magento_Checkout/js/action/get-totals',
'Magento_Customer/js/customer-data',
'domReady!'
], function ($, getTotalsAction, customerData) {

$(document).on('change', 'input[name$="[qty]"]', function(){
    var form = $('form#form-validate');
    $.ajax({
        url: form.attr('action'),
        data: form.serialize(),
        showLoader: true,
        success: function (res) {
            var parsedResponse = $.parseHTML(res);
            var result = $(parsedResponse).find("#form-validate");

            $("#form-validate").replaceWith(result);

            //reload minicart
            var sections = ['cart'];
            customerData.invalidate(sections);
            customerData.reload(sections, true);

            //reload total summary
            var deferred = $.Deferred();
            getTotalsAction([], deferred);

            
        },
        error: function (xhr, status, error) {
            var err = eval("(" + xhr.responseText + ")");
            console.log(err.Message);
        }
    });
});

});

If I update qty in cart so that the qty is higher than the quantity available. I want to display a message like "The requested qty is not available"?

Can I use customerData to show error messages and display them on the page?

Thanks.

0

Go to Magento admin and edit any item. There is one link available below QTY field advanced inventory. Click on that option. There is one text field available for it.

Maximum Qty Allowed in Shopping Cart you can uncheck Use Config Settings and set QTY there.

Save that product.

Hope it will help you.

1
  • I think that's not really what I am looking for. I would like my website to show a custom message when a customer adds a quantity that exceeded the stock size. Sep 4 '20 at 14:48
0

This is how Magento is doing it in the minicart. Maybe it helps you.

https://github.com/magento/magento2/blob/2.4/app/code/Magento/Checkout/view/frontend/web/js/sidebar.js#L213

0

Finally was able to fix issue. I just had to reload the message after setting CustomerData message section.

//Display error if found after jquery
            var messages = $.cookieStorage.get('mage-messages');
            if (!_.isEmpty(messages)) {
                customerData.set('messages', {messages: messages});
                $.cookieStorage.set('mage-messages', '');
            }

            //reload messages section
            var messages_section = ['messages'];
            //customerData.invalidate(messages_sections);
            customerData.reload(messages_section);

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.