views:

16

answers:

2

Hello I am working on getting data from database by sending a piece of value using the getJSON method of JQuery library, to a PHP function which fetches data from the database. The data is then put into an name:value pair array and is json encoded and returned/echoed. This would help jQuery to populate the required HTML elements with the data from database. This works fine for me.

My problem is to have login redirection when the user is not logged in or when the session is expired. I am working with cakePHP, so I use their Auth component to check if the user logged in

if(isset($this->Auth->User('id')))
{
//do reqd
}
else
{
$this->Session->setFlash(__('Session Expired.', true));
$this->redirect(array('controller'=>'users','action' => 'login'),null,true);
}

And when the the session is expired, the login page is actually displayed as html in the json response, rather than the whole page being redirected. I know it is coming as a json response as I can see the login page displayed in the HTML part of firebug's console application. I am not sure if there needs to be any other type of redirection.

+1  A: 

Not sure how to do this specifically in Cake, but the general approach is to look for an HTTP header which is usually sent by browsers when using XHR:

X-Requested-With: XMLHttpRequest
Robin
Hello Robin, could you explain what that header is?? or what its name is?
macha
Here's the function I use: `function isAjaxRequest() { return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) }`
Robin
Thanks a lot!!!
macha
+1  A: 

Hello,

the only way I found to manage this is that on the server side, if session expired, I didn't launch the AJAX request but return a normalized JSON object to say that session expired and manage the redirection on the client side via AJAX.

Server:

// If $_SESSION expired
echo json_encode(new array("session" => "expired"));
exit(0);

Client:

success: function(data) { if(data && data.session) { /* Session expired */ } }

Whitout doing like this, if dataType is set to JSON, request will fail and go to the error callback with error "Invalid JSON".

Arnaud F.