Redirect with Ajax

In my current project I have a login form I want to validate with Ajax. If everything is ok, the user should be redirected to the respective start page. As it seems to be impossible to do the redirect on the server-side (at least to me), I do it on the client-side. I use the following snippet in my view:

<div id="login">
    <?php echo $ajax->form(array('action' => '/login'), 'post', 
                                              array('update' => 'login')); ?>
    ...
    </form>
    <?php if (isset($url)) echo $javascript->codeBlock('window.location = "'.$url.'"'); ?>
</div>

And in my controller I use the following code:

if ($this->RequestHandler->isAjax())
{
    $this->set('url', '/'.$page);
}
else
{
    $this->redirect($page);
}

5 Comments

  1. Nate
    Posted March 15, 2006 at 10:17 am | Permalink

    If you are redirecting within the same controller, you can use Controller::setAction( ). You pass it the name of the action you want to use, along with any parameters to pass it.

    Just remember to return after calling it, so your current action does not continue.

  2. Posted March 16, 2006 at 8:57 am | Permalink

    @Nate: Thanks for the hint. For the current form I cannot use this function as I redirect to other controllers, but maybe in another situation that function would be helpful.

  3. Posted May 16, 2006 at 12:52 am | Permalink

    For me, in most cases

    $this->redirect(‘/ajax/controller/action’);

    (e.g. $this->redirect(‘/ajax/users/index’); ) works fine. Of course only the content inside the that is updated by Ajax is reloaded.

    If you need a complete site-reload or -relocation the suggested javascript-method seems to be needed.

    Thanks anyway for the tip, I’m using it!

  4. Posted December 6, 2006 at 1:49 pm | Permalink

    Oh thank you c_t that was the solution i searched all day long !

  5. tiago
    Posted February 14, 2008 at 8:52 pm | Permalink

    tnx for sharing!


Post a Comment

Required fields are marked *
*
*

%d bloggers like this: