Question

I've done a user registration and login system on PHP. It works fine but now I'm trying to send the POST request with Ajax to stay in the same page and the responseText returns empty. I've tried some solutions I've seen in similiar questions but none of them has worked for me.

This is the php function I use to log in the user:

if(!empty($_POST)) { 
    $query = " 
        SELECT 
            id, 
            username, 
            password, 
            salt, 
            email 
        FROM users 
        WHERE 
            username = ? 
    "; 

    try {  
        $stmt = $db->prepare($query); 
        $stmt->bind_param("s", $_POST['username']);
        $result = $stmt->execute(); 
    } 
    catch(Exception $ex) { 
        die("Failed to execute the query"); 
    } 

    // Is logged in? 
    $login_ok = false; 

    $res = $stmt->get_result();
    $row = $res->fetch_assoc();

    if($row) { 
        // Hash the submitted password and compare it whit the hashed version that is stored in the database
        $check_password = hash('sha256', $_POST['password'] . $row['salt']); 

        for($n = 0; $n < 65536; $n++) { 
            $check_password = hash('sha256', $check_password . $row['salt']); 
        } 

        if($check_password === $row['password']) { 
            $login_ok = true; 
        } else {
            echo "Incorrect password";
        } 
    } 

    if($login_ok) { 
        unset($row['salt']); 
        unset($row['password']); 

        $_SESSION['user'] = $row; 

        echo "Logged in";
    } else { 
        echo "Login failed";
    } 
}

And this is my form and Ajax function:

<form action="" method="post">
    <fieldset>
        <legend>Login</legend>
        <input type="text" name="username" placeholder="user" value="" />
        <input type="password" name="password" placeholder="pass" value="" />
        <input type="button" id="log" value="Login" onclick="log()"/>
    </fieldset>
</form>

<script type="text/javascript">
    function log(){
        if (!window.XMLHttpRequest) return;
        var url = "php/login.php",
            req = new XMLHttpRequest();

        req.open("POST", url);
        req.send(null);

        req.onreadystatechange = function(){
            if(req.readyState == 4 && req.status == 200){
                var response = req.responseText;
                alert(response);
            }
        } 
    }
</script>

Any ideas?

Edit: I'm trying not to use jQuery btw.

Was it helpful?

Solution

Added answer here so that it can be accepted and so that other SO users don't hit this page thinking it's an unanswered question.

The problem in your example code is that no POST data is being sent with the AJAX request.

Therefore your first condition: if (!empty($_POST)) equals FALSE and as a result none of the code within the condition is run.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top