April 12, 2012

php not redirecting

Question by NSchulze

I’m trying to write the logout of a website. When I do this I want the page to redirect to the login page. I think I’m doing it the correct way, but can’t get the right result. Could you guys point me in the right direction?

Relevant Code:

<button onclick="logout()">Logout</button>

function logout()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.location=xmlhttp.responseText;
}
}
xmlhttp.open("GET","logout.php",true);
xmlhttp.send();
}

<?php
session_destroy();

header("Location:http://localhost:8888/loginns.html");

mysql_close($con);
?>

Thanks!

Answer by Starx

You are sending an ajax request to the page. But you are redirecting in the PHP script. That will have no effect.

You should redirect in the JavaScript after the ajax request like

window.location = 'http://localhost:8888/loginns.html';

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!