1

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;
    die($msg);
}

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

$cnt = mysql_num_rows($ret);
if($cnt == 1) {
    session_start();
    $_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();
        obj.open("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);
                }
            }
        }
        obj.send(params);
1
  • the XMLHttpRequest object has a property onload, so you don't have to check the status and readystate :) Commented Feb 8, 2014 at 22:42

4 Answers 4

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Did you mean that I have to do the redirection on the Javascript?
3

You need to take out the echo statement before header(). Header won't work if anything has been output to the browser before it is called.

Here's the php doc on that.

Comments

0

What's happening exactly?

After header() is called in php, php still executes the rest of the script unless you stick an exit; after the header() call. This is only if you don't want to execute the rest of login.php

1 Comment

weirdly it open a pop up window displaying the HTML script for the login page (another page called index.php) . And for the login.php that's the last line on the code so I don't think exit is necessary.
0

You can one thing replace your code header("Location: profile.php"); by echo "window.location.href='profile.php'; and replace your success function as

     if(obj.status == 200) {
         eval(obj.responseText);
     }

Thats it. now a response will be evaluated by script and will redirect your page on profile.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.