🔥 Just Launched! Werra Premium Template for HyväSee it in Action

Magento 2 Add Success or Error Message Using JS (JQuery)

By Chandresh ChauhanUpdated on Apr 18, 2025 3 min read

Do you want to display a success message or error in Magento 2 using JQuery? Read this complete tutorial to learn how.

Magento 2 error or success messages are a great way to communicate with users and provide feedback based on their interactions. Showing effective messages can help improve the user experience of the storefront. Here’s what the error/success messages look like:

Magento 2 Error Success Message Using JavaScript

You can use the controller in Magento 2 to display messages to users. However, it generally operates within the traditional request-response cycle, typically used for page reload actions. But what if you want to display an error message without reloading the page in Magento 2? The solution is to make an AJAX request using JS JQuery to display a success or error message in Magento 2.

In this tutorial post, learn to use JavaScript to display a page message in Magento 2.

Method to Display Magento 2 Error or Success Message Using JQuery

We can use Magento’s customer data JavaScript object to display messages using AJAX. Here’s the script to display Magento 2 ajax success message or error message:

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

    customerData.set('messages', {
        messages: [{
          text: 'error message to display'
          type: 'error',
       }]
   });
});

You can modify the above script to add the message text and set its type to success or error. And set it within your frontend logic to add  Magento 2 show error message or success message.

That’s it!

In case you’ve any doubts about how to add success message in Magento 2, feel free to ask in comments. I will be happy to help you!

Thanks for reading.

Chandresh Chauhan Full Image
Article byChandresh Chauhan

He has been with Meetanshi for more than three years now as a certified Magento developer. A silent guy whom you can always find solving clients' issues, is an avid reader too.