In my componenent on Joomla! 4, when i do an ajax request and that ajax request return an error or exception, i'am wondering how to display it into enqueuemessage.
Is-there a way to do it ?
Thanks by advance
In my componenent on Joomla! 4, when i do an ajax request and that ajax request return an error or exception, i'am wondering how to display it into enqueuemessage.
Is-there a way to do it ?
Thanks by advance
When you say "display it into enqueuemessage" I'm assuming that you want to display it in the same message area that enqueueMessage displays in. You can do that in your javascript by calling Joomla.renderMessages()
, which is a function in the Joomla core.js source file.
The easiest way to get it to work is to use the JResponseJson class to handle the JSON response. See https://docs.joomla.org/JSON_Responses_with_JResponseJson for a description.
So in your Ajax handling server code:
use Joomla\CMS\Factory;
$app = Factory::getApplication();
$app->enqueueMessage("Enqueued notice", "notice");
echo new JResponseJson("some response data", "some response message", false, false);
Provided the 4th parameter ($ignoreMessages
in the API) is set to false (and it is false by default), JResponseJson will copy the enqueued messages into the Ajax response (and clear them from the session).
The above will result in an Ajax response
{"success":true,"message":"some response message","messages":{"notice":["Enqueued notice"]},"data":"some response data"}
Then in your javascript code which handles the Ajax you can do something like:
jQuery.ajax({
… // your request data
})
.done(function(result, textStatus, jqXHR)
{
...
Joomla.renderMessages(result.messages);
});
You can find the code of a sample component demonstrating this at https://docs.joomla.org/JSON_Responses_with_JResponseJson#Sample_Component_Code. I verified that this worked on my Joomla4 instance.
If you don't use JResponseJson, then provided you've got the messages section of the Ajax response JSON-encoded in the same way as JResponseJson does, then you can obviously still use Joomla.renderMessages()
on it.
$app->enqueueMessage(JText::_('JLIB_DATABASE_ERROR_DATABASE_CONNECT'), "error");
. The message should then appear translated ok.
Commented
Jan 11, 2020 at 20:51
For future readers, I found that Joomla (at least in version 3) does not save the message queue, unless the $application->redirect()
function is called. Usually, Ajax requests end with $application->close()
, so any enqueueMessage
called is lost.
I added these two lines before calling $application->close()
in my ajax controller, to make the message queue persist until the next page load:
$session = \JFactory::getSession();
$session->set('application.queue', $app->getMessageQueue());
Again, this code is for Joomla 3. It may work in Joomla 4, but I haven't tested it.