简体   繁体   中英

Unable to login using html5, AJAX and PHP

I am trying to login into a user account using a html form, with AJAX and PHP spent hours searching for solutions but could not find anything. I am new to AJAX and php so would like it if someone could help me!! It does send the request to the server (WAMP) but does not send back a response..

 hthml5 form

<div id="Text">

<form action="JavaScript:loginAccount()" id="loginForm">
<h1>Login into My Account</h1>
Username:<input id="username" type = "text"  value="" /><br><br>
Password:<input id="password" type = "text"  value="" /><br><br>
<div class="buttons">
<input type="submit" id="" value="Login" />
<input type="button" id="" value="Cancel" onclick="returnMain()"/>
</div>
</form>


AJAX Request to the php file

var loginAccountRequest = new XMLHttpRequest(); 

function loginAccount() {
var url = "login.php";
var userName = document.getElementById("username").value;
var passWord = document.getElementById("password").value;
loginAccountRequest.onreadystatechange = insertStock();
loginAccountRequest.open("POST", url, true);
loginAccountRequest.setRequestHeader("Content-type", "application/x- www-form-urlencoded");
loginAccountRequest.send("user="+userName+"&pass="+passWord);
}

AJAX response from the server

function insertStock() {
if (loginAccountRequest.readyState == 4) {
if (loginAccountRequest.status == 200) {
var response =  loginAccountRequest.responseText;
var thediv = document.getElementById("Text");
if(response==0){
thediv.innerHTML = "Sorry please try again.." 
} 
if(response==1){
stockShort();
 }
}
}
 }

php file

<?php
$uname = "";
$pword = "";
$errorMessage = "";
$num_rows = 0;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
}

$link = mysqli_connect('localhost', 'username', 'password','database');


//Grab User submitted information
$users = $_POST['user'];
$passwd = $_POST['pass'];
$sql = "SELECT * FROM users WHERE username = $users AND password =   $passwd";
$result = mysqli_query($link,$sql);

if ($result) {
}
else { $errorMessage = "Error logging on";

}
$num_rows = mysql_num_rows($result);

if ($num_rows > 0) {

$errorMessage= "logged on ";

}else {
$errorMessage= "Invalid Logon";
}
mysqli_close($link);
?>

First of all, in your JavaScript you aren't correctly assigning a callback for the AJAX call. Use:

loginAccountRequest.onreadystatechange = insertStock; //no parentheses

Second, your PHP doesn't respond with anything. Put this at the end of your PHP code:

echo $errorMessage;

Third, your callback code doesn't properly check the response . Instead of checking for 0 or 1 , do:

if (response !== "logged on ")
    thediv.innerHTML = "Sorry please try again..";
else
    stockShort();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM