Skip to main content
1 of 11

User notifications using messenger and ajax

I would like to send a message to the user on an event in the backend without a refresh. I have a 2fa login form that will send a token text. That form has a "did not recieve sms" button/link using ajax that causes the text to be sent again. I would like to inform the customer of the incoming message.

There is the MessengerInterface, which you can be used to send notifications to the user. But this requires a refresh to actually show the message.

\Drupal::messenger()->addStatus('Some conditional message to the user');

I imagine there is a way to send the message to the user using ajax/XHR? Which would not require a refresh, to inform the user of the impending text.

My form has a wrapping div which I can target, the button/link has an '#ajax' element with, as far as I know, all the prerequisite elements:

'#ajax' => [
  'callback' => '::ajaxCallback',
  'event' => 'click',
  'wrapper' => 'twofa_wrapper',
],

I found this comment on the Drupal forum but using this code, with obvious replacements, does nothing apart from sending a XHR responce, visible in the network tab. The json response contains a number of things one being the html for the form which contains the message that I would like to show, but it doesn't show this content on the actual page.

public function ajaxCallback(array &$form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  $message = [
    '#theme' => 'status_messages',
    '#message_list' => \Drupal::messenger()->all(),
  ];
  $messages = \Drupal::service('renderer')->render($message);
  $response->addCommand(new HtmlCommand('#result-message', $messages));
  $response->addCommand(new ReplaceCommand('#twofa_wrapper', $form));
  return $response;
}

What am I missing?