开发者

PHP- Ajax and Redirect

开发者 https://www.devze.com 2023-01-22 09:01 出处:网络
ihave 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开发者_如何学Go is not active i want to redirect the user to anot

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开发者_如何学Go 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


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.


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;


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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消