The PHP () header called via AJAX does not work properly


I'm new to web development.

Right now I'm working on a login feature on a site. I used Javascript/AJAX to fetch the username and password and send it to a PHP file for verification on the MYSQL database. That's what I'm about to make.

My question is why can't the header() function working properly? I want after the user login she is redirected to the profile page (profile.php)

Here's snippet of the PHP (login.php):

$query = "SELECT * from user WHERE username = '$uname' AND password = md5('$pass');";
$ret = mysql_query($query) or die(mysql_error());

if(!$ret) {
    $msg = "Invalid query " . mysql_error() . "\n";
    $msg .= "Whole query " . $query;

$userid = -1;
while($row = mysql_fetch_array($ret)) {
    $userid = $row["ID"];

$cnt = mysql_num_rows($ret);
if($cnt == 1) {
    $_SESSION["userid"] = $userid;
    $_SESSION["uname"] = $uname;
    echo "You have logged in successfully!";
    header("Location: profile.php");
} else {
    echo "Wrong Username/Password";

And here's for the Javascript (an AJAX function):

var obj;
    var url = "login.php";
    var params = "uname=" + document.getElementsByName("uname")[0].value + "&pass=" + document.getElementsByName("pass")[0].value;
    if(window.XMLHttpRequest) { // Major browsers
        obj = new XMLHttpRequest();"POST",url,true);
        obj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        obj.setRequestHeader("Content-length", params.length);
        obj.setRequestHeader("Connection", "close");
        obj.onreadystatechange = function() {
            if(obj.readyState == 4) {
                if(obj.status == 200) {
                    // success
                } else {
                    alert("Problem in returned data" + "Error status=" + obj.status);

I don't think the redirect will work with AJAX. This is what will happen:

  1. AJAX request is sent to login.php
  2. login.php sends back a header with Location: profile.php
  3. The browser then redirects and fetches profile.php
  4. The results of profile.php is then passed to your XMLHttpRequest Object.

A way to get the AJAX response to redirect your page is to do this:

  • The response from login.php returns a JSON response containing the status code (302 or 301) and the location to redirect to.

  • The response itself has a status code of 200 (successful).

  • The process the JSON response and check the status code for 302 or 301 and redirect to the location.