When setting the form with ajax handler like this

  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['actions']['submit'] = array(
      '#ajax' => [
        'wrapper' => 'custom_form_wrapper',
        'callback' => '::ajaxCallback',

and trying to set the redirect on submitForm

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $url = 'https://example.com';
    $form_state->setResponse(new \Drupal\Core\Routing\TrustedRedirectResponse($url, 302));

nothing happens and no error message appears but the form seems like it has finished processing.

When the ajax part is taken out the action:submit array the form redirects properly on submit. What should be done differently ?

1 Answer 1


You can't return a redirect response, because the ajax script in the browser expects a json array with jquery commands, so you need to return a RedirectCommand from the ajax callback:

  public function ajaxCallback(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();

    $command = new RedirectCommand('https://example.com');

    return $response->addCommand($command);

which then assigns window.location to redirect client-side.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.