tags:

views:

48

answers:

5

i have a jquery Ajax request happening on a page. On php side i am checking if the session is active and doing something. If the session is not active i want to redirect the user to another page in php(header redirect). how do i do it.

I know how to achieve it in javascript(i.e if session_fail then change window.location but is there something that i can do in php/cakephp

A: 

Just add a header statement like this in your PHP page.

header("Location: http://www.example.com/");

However, since you are invoking the PHP with AJAX you will need to detect the redirect response and redirect the page manually from Javascript.

Hannes de Jager
Why the downvotes? I thought what I mentioned here is in concept the same as the answer of Nev Stokes ?
Hannes de Jager
+3  A: 

Redirects only say "The data you requested can be found here".

HTTP provides no way to say "Even though you requested a resource to go inside a page, you should should leave that page and go somewhere else".

You need to return a response that your JavaScript understands to mean "Go to a different location" and process it in your own code.

David Dorward
A: 

Use Header("http://url.com/")

Ash Burlaczenko
+1  A: 

If I understand what you want to happen then this is how I'm implementing it. It's in Prototype instead of jQuery but it shouldn't take you long to translate:

new Ajax.Request('process.php', {
    on401: function(response) {
        var redirect = response.getHeader('Location');
        document.location = redirect;
    }
});

In your PHP, output the following if the session is inactive:

header('Location: http://example.com/login.php', true, 401);
exit;
Nev Stokes
+1  A: 

This is what you would want in your php IF THIS WERE A REGULAR REQUEST, NOT AN AJAX

if (isset($_SESSION)) doSomething();
else header("Location: otherUrl");

Since this is an Ajax call, you are not passing control to the php, but just trying to get a response that (likely) fills a particular section of your page. You do not mention what jQuery ajax function you use, but it matters. I would imagine you are using either $.get() or $(element).load() ??

Without knowing the particulars, this is my best suggestion for you.

Ajax call: $.get(url, callbackFunc);

php:
if(isset($_SESSION)) echoSomething()
else echo("redirect");

callbackFunc:
function(data) {if (data == "redirect") window.location = otherUrl; else $("#desiredElement").html(data);}

jon_darkstar