5

I want to redirect the page in the ajax callback function, and nothing (like "header", "drupal_goto" etc.) works for redirect in the ajax callback function.

3 Answers 3

7

There are two methods for it and the most suitable one (adding a Drupal.behaviors object via javascript ) is as below

(function ($) {
  Drupal.behaviors.custom_redirect = {
    attach: function() {
      // Replace he form id and the select id in selecotor below.
      $("form#form_id select#select_id").change(function(e) {
        e.stopPropagation();
        // Path where you want to redirect.
        var redirect_url = 'YOUR_REDIRECT_URL';
        window.location.pathname = redirect_url;
      });
    }
  };
}(jQuery));

However if you specifically want to perform the above in you PHP code/custom module than you may try adding the following snippet(using ctools ajax redirect command) to your ajax callback function:

$redirect_url = 'YOUR_REDIRECT_URL';
ctools_include('ajax');
ctools_add_js('ajax-responder');
$commands[] = ctools_ajax_command_redirect($redirect_url);
print ajax_render($commands);
exit;
7

If you've got ctools installed (nearly all Drupal sites do), you can make use of ctools_ajax_command_redirect() in your AJAX callback, e.g.

ctools_include('ajax');
$commands[] = ctools_ajax_command_redirect('path/to/redirect');
return array('#type' => 'ajax', '#commands' => $commands);
1
  • Looks great @Clive, but I could'nt get it working within views_pre_render : if ( $view->name == 'FOO' && $view->current_display == 'BAR' && count($view->result)==1 ){ if(is_numeric($view->result[0]->nid)){ //drupal_goto('node/' . $view->result[0]->nid); ctools_include('ajax'); $commands[] = ctools_ajax_command_redirect('node/' . $view->result[0]->nid); return array('#type' => 'ajax', '#commands' => $commands); } } I'm surely missing something :(
    – Kojo
    Jun 17, 2016 at 18:32
-1

in your drupal callback function add javascript window.location.href = "path";

ex: if your callback is ajax_call_back() then,

 `function ajax_call_back($form, $form_state){

return 'window.location.href = "http://www.google.com";'exit;

} ` note: you should add SCRIPT tag in rerutn before window.location.href = "http://www.google.com";

Your Answer

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