I am trying to return an ajax response when a user logs in while the page is loading post-login.

/#1 approach was attaching an ajax callback to the user login form submit with form_alter. However this callback fires right on submit and I need an ajax callback to fire after the front page loads post-login.

/#2 approach, I made a user login event and subscriber instantiated during hook_user_login. This works perfectly, I can do a drupal_set_message after a user logs in. But how would I return an ajax response from the event subscriber?

eventsubscriber peared down

   * {@inheritdoc}
  public static function getSubscribedEvents() {
    return [
      UserLoginEvent::EVENT_NAME => 'onUserLogin',

   * Subscribe to the user login event dispatched.
   * @param \Drupal\gary_custom\Event\UserLoginEvent $event
   *   Dat event object yo.
  public function onUserLogin(UserLoginEvent $event) {
    //$response = new \Drupal\Core\Ajax\AjaxResponse();
    //$response->addCommand(new \Drupal\Core\Ajax\AlertCommand('test'));
    //return $response; does not work
    drupal_set_message(t('Testy testy')); //works
  • 2
    An Ajax response is requested by js code in the browser targeting a route and controller in Drupal. Why would you want to return it from an event subscriber?
    – 4k4
    Apr 24 '19 at 18:35
  • 2
    There's not really such a concept as an AJAX response, just an AJAX request - and that's made by JavaScript. So if you need to invoke an AJAX request from the post-login page, you need to inject some JavaScript into that page to make that request.
    – Clive
    Apr 24 '19 at 18:36
  • thanks, I guess that was my misunderstanding then. Any clues on how I would inject an ajax request only once after the user logs in? I wonder if theres a way I could inject an empty container with hook_user_login and just listen for that and then perform an ajax request Apr 24 '19 at 18:43
  • If you're happy with quick and dirty...make a service with two methods: setLoggingIn and getLoggingIn, which set and get a variable (whose default value is FALSE) in the class respectively. In the event subscriber, call $your_service->setLoggingIn(TRUE);, and in an implementation of hook_page_attachments_alter(), call if ($your_service->getLoggingIn()) {. If the condition passes, add a library which references a JS file that performs the AJAX request to the attachments array
    – Clive
    Apr 24 '19 at 18:56
  • 1
    You might be approaching what you're trying to accomplish the wrong way. What's the reason behind this? mind sharing what exactly you're trying to do in non-code speak?
    – No Sssweat
    Apr 25 '19 at 11:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.