Drupal - Status messages with AJAX

You can render the status messages and send them as anohter AJAX command.

For example:

$commands = array();

// Add other commands

$commands[] = ajax_command_prepend('div#ajax-status-messages-wrapper', theme('status_messages'));

return array('#type' => 'ajax', '#commands' => $commands);

At least this is the way I solved this problem when I faced it.


For Drupal 8 it's

$response = new AjaxResponse();    
$status_messages = array('#type' => 'status_messages');
$messages = \Drupal::service('renderer')->renderRoot($status_messages);
if (!empty($messages)) {
  $response->addCommand(new PrependCommand('.your_selector', $messages));
}

return $response;

For Drupal 8 form with AJAX, answer by Tim Bozeman worked, but messages were showed up with no styling. This is what worked for me:

$response = new AjaxResponse();
drupal_set_message($action);
$form['messages']['status'] = [
  '#type' => 'status_messages',
];
$response->addCommand(new InsertCommand(null, $form['messages']));

return $response;