Resolving Message Issues After AJAX Form Submission in Magento 2
Hello everyone! Today, I’m going to address a common issue faced by developers working on Magento 2 projects: message failures after performing an AJAX form submission in the admin backend.
The Problem: Missing Messages After AJAX Save
If you’re creating a custom grid or form in the Magento 2 admin panel and using AJAX for saving data, you might encounter this frustrating problem. After successfully submitting the form via AJAX, no messages are displayed to indicate whether the operation was successful or not.
In our scenario, we have a stock taking form where we allow admins to update product quantities. We’re using both JavaScript (jQuery) and PHP to handle the form submission and process the data on the server side. Here’s a breakdown of what’s happening:
-
The Controller: When the
saveaction is triggered, it receives the posted data ($data), retrieves the product ID, updates the stock quantity using the_stockRegistry, saves the changes, and attempts to display success or error messages using$this->messageManager. -
The JavaScript: On form submission (triggered by clicking a specific button), we’re using jQuery to send an AJAX POST request with the form data (
skuandqty) to the controller’s URL.
The Root Cause: Missing Message Display
After the AJAX call is successful, you would expect to see either a success or error message displayed on the screen. However, this doesn’t happen because the default Magento 2 behavior for displaying messages after an AJAX request requires a special script inclusion and the use of Magento’s Magento\Backend\Model\Session class.
The Solution: Proper Message Display After AJAX
To resolve this issue, we need to ensure that the message is properly rendered on the client side after the AJAX response is received. Here are the steps:
Step 1: Include the Required JavaScript File
In your custom admin layout XML file (e.g., adminhtml_default.xml located in the main app area), make sure you include the following script at the end of the <body> tag:
<block type="core/text" name="messages">
<action method="setText"><text><![CDATA[<script type="text/javascript">require(['jquery', 'Magento_Ui/js/core/message'], function($, message) {
jQuery(document).ready(function(){
let messages = message.list();
if (messages.get()) {
$.each(messages.get(), function(index, error) {
if (error.indexOf('error') != -1) {
console.log(error);
} else {
console.log(error);
}
});
}
});
});</script>]]></text></action>
</block>
This script includes the Magento_Ui/js/core/message module and checks for any messages stored in the session after the page is loaded (or reloaded).
Step 2: Clear the Message Session After AJAX
To ensure that the message is displayed only once and not repeated on subsequent actions, you should clear the message from the session immediately after it’s successfully rendered. Update your controller as follows:
public function execute()
{
// ... (your existing code)
if ($this->getRequest()->isAjax()) {
$result = ['success' => true];
if ($message = $this->messageManager->getMessages(true)) {
foreach ($message->getItems() as $item) {
$result['messages'][] = [
'type' => $item->getType(),
'text' => __($item->getText())
];
}
}
$this->messageManager->deleteMessagesByArea('adminhtml');
}
return $result;
}
In this updated controller, we check if the request is an AJAX call and prepare a response with any messages that are present in the session. After sending the response, we clear the message from the session using $this->messageManager->deleteMessagesByArea('adminhtml').
Conclusion
To successfully display messages after performing an AJAX form submission in Magento 2, you need to ensure proper communication between the client and server side.
Remember to include the required script in your layout XML file to handle message rendering on the client side. Additionally, make sure to clear the message from the session immediately after it’s successfully displayed or processed by the controller.
Always refer to the official Magento 2 documentation for more information on best practices for working with messages and AJAX in the admin backend: Magento 2 Developer Documentation.
If you found this explanation helpful, feel free to explore our other blog posts at Laravel Company for more insights into Magento development and e-commerce best practices.
Happy coding!