Error messages aren't displayed when submitting the form I want to display an error message when I submit a form. I added an AJAX callback to the form, and the error message appears after I refreshed the page.

I first tried the following code, but it doesn't work.

$response = new \Drupal\Core\Ajax\AjaxResponse();
$message = drupal_get_messages();
$output = $response-&gt;addCommand(new \Drupal\Core\Ajax\PrependCommand(".region-highlighted",$message));
return $output;


I also tried the following code.

$status_messages = array('#type' =&gt; 'status_messages');
$text = \Drupal::service('renderer')-&gt;render($status_messages);
return $text;
this works for form messages (in a regular ajax form callback):

    $form['status_messages'] = [
      '#type' =&gt; 'status_messages',
      '#weight' =&gt; -10,
    ];
    $response-&gt;addCommand(new ReplaceCommand('#yourFormWrapperElement', $form));


but using drupal_get_messages() screw's things somehow up .... sometimes. plus you need enable showing messages here: /admin/config/development/logging

So - your second try should also work !

$status_messages = array('#type' =&gt; 'status_messages');
$text = \Drupal::service('renderer')-&gt;render($status_messages);
return $text;


Maybe the mentioned settings are needed ..