0

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.

4 Answers 4

2

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);
0

On checkout you can use the magento's default Message component Magento_Ui/js/model/messageList and use the method addSuccessMessage or addErrorMessage based upon your response.

You can refer below code also

define([
'jquery',   
'Magento_Checkout/js/action/get-totals',
'Magento_Customer/js/customer-data',
'Magento_Ui/js/model/messageList', // added component
'mage/translate', // for support translation
'domReady!'
], function ($, getTotalsAction, customerData,messageList,$t) {

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

            messageList.addSuccessMessage({ message: $t("add your custom message") });
            
            //console.log(customerMessages);

        },
        error: function (xhr, status, error) {
            var err = eval("(" + xhr.responseText + ")");
            // added error message 
            messageList.addErrorMessage({ message: $t("add error message which you would require") });
            //console.log(err.Message);
        }
    });
  });

 });
3
  • It is still not working, what do you mean by add your login? $t(err). I think the err is not defined, does it need to be? Sep 9, 2020 at 15:48
  • check updated answer. Sep 10, 2020 at 9:28
  • Should it show up in frontend? It is not showing up. Sep 10, 2020 at 15:17
0

try this:

define(['Magento_Customer/js/customer-data'], function (customerData) {
 customerData.set('messages', {
    messages: [{
        text: 'message to display',
        type: 'success'
      }]
  });
});
0

I know its too late, but I found it useful to share for others:

    define([
        'ko',
        'jquery',
        'Magento_Ui/js/form/form',
        'Magento_Ui/js/model/messageList',
        'mage/translate',
        'moment'
   ], function(ko, $, Component, messageList, $t, moment) {}

This is how you will include messagelist model in your JS file. And then just add like below to show any messge:

messageList.addErrorMessage({
   message: $t('Something went wrong. Please contact Support team.')
});

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.