Magento2 – How to Display Messages on Ajax Success

ajaxcartmagento2shopping-cart

What I am trying to do:

When I update the cart qty so that the qty is higher than the quantity available, I want my code to be able to show an alert ‘The requested qty is not available’ pop up or notification.

Situation now:

So I have created a custom module so that the shopping cart will automatically reload when the qty changes using AJAX.

Right now, I’m not sure why but I have to reload the whole cart page for the notification to show up (see picture).

enter image description here

What I found so far:

I think Magento/Ui/view/frontend/web/js/view/messages.js appears to be responsible for adding messages but I’m not sure. Is there any way so that I do not need to reload the whole page and it automatically gives the customer the alert on ajax change?

Also, found some things online, about customerData.get('messages'). But I’m still not able to use this on my cartQtyUpdate.js file to show the messages.

var customerMessages = customerData.get('messages')() || {},
    messages = customerMessages.messages || [];

messages.push({
    text: 'message to display',
    type: 'success'
});

customerMessages.messages = messages;

customerData.set('messages', customerMessages);

here is my whole 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);

            //for testing purpose - it returns null
            var customerMessages = customerData.get('messages')() || {};
            console.log(customerMessages);

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

 });

I think the error message shows up because it has something to do with the session messages. I think we can use this session message to show up after ajax change success. I'm not sure how to do this though.

I'm still so new to Magento, so any help would be appreciated. Thank you.

Best Answer

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);
Related Topic