0

How can I redirect to a specific page in an ajax callback using Drupal 7, I've already tested this method:

function my_ajax_callback($form, &$form_state) {
  if (!user_is_anonymous()) {
    return $form['my_fieldset'];
  }
  else {
    drupal_goto('login');
  }
}

but that code doesn't redirect to /login when current user is anonymous.

  • Do you know that the function is called. Try to call a die statement to see if it is called. – Jdrupal Jan 3 at 16:19
  • Even die() in an ajax callback can't be used it will generate only an ajax error popup, ajax callback should return something as I guess but using drupal_goto() does not return any statement, so no change will be applied while calling drupal_goto(), the redirection should be done differently I guess but I don't have any idea how to resolve that. – MiharbKH Jan 3 at 16:29
  • Isn't it because ajax callbacks are handled on the system/ajax menu route and thus issuing a goto won't have any effect? I would see if you could set a form state property and check that value in the form building method, if TRUE, try the goto. – Kevin Jan 3 at 16:44
  • Smart idea Kevin but sadly it generate an ajax error popup too, this time the source path of error is /system/ajax, what I did is in my_ajax_callback() I add $form_state['redirect'] = TRUE; instead of drupal_goto() call, and in my form builder I add if (isset($form_state['redirect']) && $form_state['redirect']) { drupal_goto('login'); } – MiharbKH Jan 3 at 17:00
0

I had the same problem. You should try this:

ctools_include('ajax'); 
ctools_add_js('ajax-responder');
$commands[] = ctools_ajax_command_redirect('login');
return array('#type' => 'ajax', '#commands' => $commands);

Your Answer

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

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