Man LEE Man LEE - 27 days ago 15
Ajax Question

Jquery/ajax login form failed (if/else seems not function in ajax)

I'm new to jQuery.
I'm writing a login form for my webpage.
I want to have my login page showing login fail if the users have wrong username or password and they are allowed to go to the index.php if they log in successfully.
It works perfectly without the jQuery. However, with the jQuery, the script seems run through the if and else script and not going to redirect my webpage into the index.php
Here is the login.js

$(document).ready(function(){
$("#ack").css('display', 'none', 'important');
$("#submit").click(function(){

username=$("#username").val();
password=$("#password").val();
if(username==''||password==''){
$("#ack").css('display','inline','important');
$("#ack").html("Please enter your username and password!");
}
else{


$.ajax({

type: "POST",
url: "User/login.php",
data: "username="+username+"&password="+password,

beforeSend: function(){
$("#ack").css('display', 'inline', 'important');
$("#ack").html("Loading...");
},
success: function(html){

if(html==='login'){
$("#ack").css('display', 'inline', 'important');
$("#ack").html("<font color='green'>log in</font>");
window.location="index.php";
}
else{
$("#ack").css('display', 'inline', 'important');
$("#ack").html("<font color='red'>Wrong username or password!</font>"+html);
//I tried to output the html and found that, with 'return false;'
//below, it will not redirect and finally shown that
//Wrong username or password!login (if the username and password are correct
//if i removed the return, the sentence will still be seen with a quick refresh
//It doesn't depend on the username and password correct or not.
//I will be redirected to my index.php if they are correct.

}
}
});


}
return false;
});


});

Here is the loginform.php:

<form action="./" method="post" id="loginForm">
<div class="container">
<label><b>Username:</b></label>
<input type="text" placeholder="Enter Username" name="username" id="username" required>
<label><b>Password:</b></label>
<input type="password" placeholder="Enter Password" name="password" id="password" required>
<!--<button class="w-button" id="submit" name="submit">login</button>-->
<input type="submit" value="login" class="w-button" id="submit">
<input type="reset" class="w-button">
</div>
</form>




Here is the login.php:

<?php
require("common.php");
$submitted_username = '';
if(!empty($_POST))
{

$query = "
SELECT
id,
username,
password,
salt,
email
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $_POST['username']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$login_ok = false;
$row = $stmt->fetch();
if($row)
{

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

if($check_password === $row['password'])
{

$login_ok = true;
}
}


if($login_ok)
{

unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo("login");
}
else
{
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
echo("nologin");
}
}
?>

Answer

Your missed add var before variable name like this

username=$("#username").val();
password=$("#password").val();

it should be like bellow :

var username = $("#username").val();
var password = $("#password").val();

Also your data url was incorrect like bellow :

data: "username="+username+"&password="+password,

it should be data: {username:username, password:password},

You missed e.preventDefault(); after $("#submit").click(function(e){

Your correction code bellow :

<script>
$(document).ready(function(){
    $("#ack").css('display', 'none', 'important');

    $("#submit").click(function(e){
        e.preventDefault();
        var username = $("#username").val();
        var password = $("#password").val();

        if(username=='' || password==''){
            $("#ack").css('display','inline','important');
            $("#ack").html("Please enter your username and password!");
        } else {

            $.ajax({
                type: "POST",       
                url: "User/login.php",
                data: {username:username, password:password},
                beforeSend: function(){
                    $("#ack").css('display', 'inline', 'important');
                    $("#ack").html("Loading...");
                },
                success: function(html){
                    if(html==='login'){
                        $("#ack").css('display', 'inline', 'important');
                        $("#ack").html("<font color='green'>log in</font>");
                        window.location="index.php";
                    }
                    else{
                        $("#ack").css('display', 'inline', 'important');
                        $("#ack").html("<font color='red'>Wrong username or password!</font>"+html); 
                        //I tried to output the html and found that, with 'return false;'
                        //below, it will not redirect and finally shown that
                        //Wrong username or password!login (if the username and password are correct
                        //if i removed the return, the sentence will still be seen if the username and password correct or not. 
                        //I will be redirected to my index.php if they are correct.
                    }
                }
            });
        }
        return false;
    });
});
</script>