I make a simple program to simulate authentication using AJAX and PHP. The following is my code. It will redirect to "/?" but nothing happened. I tried to use checkLogin(); return false; in onclick event but it didn't work.
index.php
<script type="text/javascript" src="validation.js"></script>
<form>
<p>
<label>Username <abbr title="Required">*</abbr></label>
<input id="usernamelogin" type="text" value="" />
</p>
<p>
<label>Password <abbr title="Required">*</abbr></label>
<input id="passwordlogin" type="text" value="" />
</p>
<p>
<input id="login" type="submit" value="Login" onclick="checkLogin()" />
</p>
</form>
validation.js
function checkLogin(){
var u = document.getElementById("usernamelogin").value;
var p = document.getElementById("passwordlogin").value;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onReadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
if(xmlhttp.responseText == u){
alert(':)');
}
else{
alert(':(');
}
}
}
xmlhttp.open("GET", "login.php?u=" + u + "&p=" + p, true);
xmlhttp.send();
}
login.php
<?php
$u = $_GET['u'];
$p = $_GET['p'];
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'db';
$con = mysql_connect($host, $user, $pass);
if(!$con) die("Could not connect: " . mysql_error());
mysql_select_db($db, $con);
$query = "select username from login where username = '" . $u . "' and password = '" . $p . "'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
echo $row['username'];
mysql_close($con);
?>
/login.phpto be sure it will perform request to the same URL independent from the current URL. Also could you check if any XHR requests are performed using the Developer tools of Chrome or Firebug for Firefox?/login.phpand it didn't work. I'm checking the XHR requests.onreadystatechangenotonReadystatechange. Unbelievable. I use auto complete feature in Notepad++.