KJ Saxena
KJ Saxena

Reputation: 21838

Redirecting browser using AJAX

Is there a way to redirect a user to a page (login page in my case) when an AJAX query is made by the user to a server? The server is supposed to serve data only if the session is set or else the user should be redirected. I have tried sending a header("location:...") request but the browser handled it as a string (xmlhttp.response) rather than acting on it.

Upvotes: 2

Views: 240

Answers (3)

Lucky
Lucky

Reputation: 646

Not directly. Your callback function would have to handle it.

For example, if the server sends the text "LOGIN;/login.php;" then your onreadystatechange call back could have the snippet

if (xmlhttp.responseText.substring(0,6) == 'LOGIN;') {
    window.location.href = xmlhttp.responseText.split(";")[1];
    return;
}

If you're using a framework for the Ajax, this code could be in whichever callback gets the result of the Ajax call.

Upvotes: 2

marcc
marcc

Reputation: 12399

No. Not directly. You can return something special which should be handled as a redirect. But since the browser isn't looking to navigate and it won't.

Upvotes: 2

rahul
rahul

Reputation: 187050

In the callback function you can set the window.location to the new page if the session is not set.

Upvotes: 1

Related Questions