Using loginRequiredAjaxResponse to solve ajax session timeout

You are viewing revision #3 of this wiki article.
This is the latest version of this article.
You may want to see the changes made in this revision.

« previous (#2)

This solution requires Yii 1.1.9 or above

The problem:

A user has no activity for a longer period of time and the php session times out. After the session has expired he makes an Ajax request and nothing happens or, in case of a grid view, the grid completely disappears.

Expected behavior:

Show the login page and redirect after successful login

The solution:

Set 'loginRequiredAjaxResponse' in your configuration (config/main.php)

...
'components'=>array(
	'user'=>array(			
		...
		'loginRequiredAjaxResponse' => 'YII_LOGIN_REQUIRED',
		...
	),
	...

In your view or template

<?php
	if (Yii::app()->components['user']->loginRequiredAjaxResponse){
		Yii::app()->clientScript->registerScript('ajaxLoginRequired', '
			jQuery(document).ajaxComplete(
				function(event, request, options) {
					if (request.responseText == "'.Yii::app()->components['user']->loginRequiredAjaxResponse.'") {
						window.location.href = options.url;
					}
				}
			);
		');
	}
?>

Note:

The code above is tested with a grid view where options.url is a useable page url. If this is not the case or you just want to show the login page with no redirect afterwards you can replace

window.location.href = options.url;

with

window.location.href = "'.Yii::app()->createUrl('/site/login').'"