How to do a redirect using ajax command in drupal 7

Want to redirect users to a new page after successfull ajax form submit? This tutorial explains how to do it easily using Drupal ajax command framework.

Ajax callback

function custom_ajax_callback($form, $form_state) {
    if(!form_get_errors()) { //redirect only if form has no errors
        $commands = array();
        
        $commands[] = array(
            'command' => 'customAjaxRedirect',
            'url' => 'http://example.com/some-page'
          );

        return array('#type' => 'ajax', '#commands' => $commands);
    }
    else {
        return $form;
    }
}

Now, we need to define the command in a js file where the actual redirect will happen on client side

(function($) {

    Drupal.ajax.prototype.commands.customRedirect = function(ajax, response, status) {
        window.location = response.url;
    }

})(jQuery);

 

Add new comment