Sébastien
Sébastien

Reputation: 1697

CakePHP 2 AJAX redirections

I'm using AJAX in my web-app stuffs like search but if the user has been logged out, the ajax function return nothing because the redirection (from the action 'search' to the action 'login') has not been handled correctly.

Is it possible to redeclare the method 'redirect' in AppController to render the right action when a redirect hapend in an AJAX call ?

Thank you, Sébastien

Upvotes: 1

Views: 1390

Answers (2)

RichardAtHome
RichardAtHome

Reputation: 4313

Another approach would be to allow everyone access to the Ajax function:

public function beforeFilter() {
  $this->Auth->allow(array('my_ajax_method'));
}

And then check the user is authenticated in the method itself:

public function my_ajax_method() {

    if (!$this->Auth->user()) {
       //user not authenticated
       $result = "requires auth";
    }
    else {
       // use is authenticated
       // do stuff
       $result = 'result of stuff';
    }

    $this->set(compact('result'));

}

You will need to check the result of the ajax call in your javascript and act accordingly.

Upvotes: 1

Dunhamzzz
Dunhamzzz

Reputation: 14798

I think your best bet would be to setup you ajax to call to respond correctly to an invalid response. As it seems to be an important part of your app I would pass a 'loggedin' variable with every ajax request, so the client can tell as soon as the user has been logged out.

Update

In the case you want to keep a user logged in, you simply have to put the logged in/cookie check in something like your AppController::beforeFilter() that gets run with every request. for example:

public function beforeFilter() {
     if($this->Auth->user() {
          // USer is logged in, it's all gravy
     } else {
         // User is not logged in, try to log them in
         $userData = $this->Cookie->read('User');
     if(!empty($userData)) {
              // Function that grabs info from cookie and logs in user
         }
     }
}

This way there will be no redirect as the user will be logged in as long as they have a cookie.

Upvotes: 2

Related Questions