Ajax and session timeout

The case: User does nothing but watching the page. After session has expired he makes an Ajax request. But Yii does nothing. It’s not redirecting to the login page why?. Any ideas? Where to control it?

The request makes jQuery function: $(’#item_id’).load(’?r=user/ajaxaction’);

Thank you all in advance.

There are many topics about it.

Any link anyway concerning Yii?

Have solved by myself using callback of jQuery ‘.load()’ function and ‘responseText’ parameter. :D

Still many people meet the problem when the DIV is loaded with loginPage instead of redirecting to it. I could not see any elegant solution. If anyone know please share.

That is the reason why I prefer to use my own JavaScript functions based on jQuery load function.

Here is the sample:

PHP Yii code




public function actionAjaxAction(){

   if(isset($_REQUEST['data']) && Yii::app()->request->isAjaxRequest) {


  ...your code...

  

  }

  if(Yii::app()->user->isGuest) {echo '0';} else {echo '1';}

}



JavaScript code




function ajaxCommand(){


...your code...


  $('#ajax_port_id').load('?r=controller/ajaxaction',{data:some_data,YII_CSRF_TOKEN:document.getElementsByName('YII_CSRF_TOKEN')[0].value},function(responseText){

	 if(responseText!='1') {

            $('#ajax_port_id').text('');//better clear of loginUrl code...

	    alert('Your session is timed out!'); 

	    window.location='?r=site/index';//or wherever...

	} else {

            ...your code...  

           $.fn.yiiListView.update('some_view_id'); //for example..     

        }

        $('#ajax_port_id').text('');

  });

}



HTML page should have <div id="ajax_port_id" style="display:none;"></div> and YII_CSRF_TOKEN hidden field.

What happens if the session timed out? The controller will redirect the user to the loginUrl and its content will be loaded into responseText (0 will be added to it also :) ),

then alert() then redirect…

This solution seems a little bit ugly but reliable enough.

But does anyone have the better way? Especially for Yii builtin ajax calls?

Thank you in advance.

Here is a good "official" Yii solution:

http://www.yiiframework.com/wiki/321/using-loginrequiredajaxresponse-to-solve-ajax-session-timeout/