LoginSignup
6
7

More than 5 years have passed since last update.

【jQuery】【CakePHP】ajaxで擬似的なリダイレクトを行う

Last updated at Posted at 2015-06-26

やりたいこと

ajaxでサーバにPOST(GET)して、結果によっては別ページにジャンプさせたい。

※そもそもやりたいこと
ajaxでサーバにPOSTしたときにAuthのセッション切れだったら、ログインページに飛ばしたい。

実装

ajaxでは大本のページをリダイレクトさせることはできないので、サーバ側ではフラグと遷移先URLを返して、クライアント側ではフラグを評価してジャンプが必要な場合は遷移先URLへジャンプする。

クライアント側
$.ajax({
  url:'isLoggedIn',
  type:'get',
  dataType:'json'
}).done(function(data){
  //ジャンプが必要かのチェック
  if(!data.isLoggedIn){
    location.href = data.url;
  }
})
サーバ側(CakePHP)
public function isLoggedIn(){
  $user = $this->Auth->user();

  //ユーザがログイン中かのチェック
  if(empty($user)){
    //ログイン中でない場合
    $res = [
      'isLoggedIn'=>false,
      'url'=>  'http://foo/bar/Users/login'
    ];
  }else{
    //ログイン中の場合
    $res = [
      'isLoggedIn'=>true,
    ];
  }

  $this->viewClass = 'json';
  $this->set(compact('res'));
  $this->set('_serialize','res');
}

ちなみに、チェック用のメソッドはAuthから外しておく。

Authの外し方
$this->Auth->allow(isLoggedIn);

参考:【CakePHP】jsonを出力する

6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7