Hi Guys,
A client has asked me to build a website with a login system. I thought it'd be a nice touch to add some AJAX in to validate the form on submit.
I just can't seem to get it to work.
Here's my HTML Form.
HTML Code:
Code:
<form name="loginForm" onsubmit="ajaxFunction()">
<p>Username
<input type="text" id="username" />
</p>
<p>Password
<input type="password" id="password" />
</p>
<div id="result"></div>
<p>
<input type="sumbit" value="Log In" /><!--I've tried this line with the onclick="ajaxFunction()" instead of on the form tag-->
</p>
</form>
Here's my J
Code:
Code:
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
var params;
//make the Ajax Object
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
var ajaxDisplay = document.getElementById('result');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
ajaxRequest.open("POST", "login.php");
ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajaxRequest.send('username=' + username + '&password=' + password);
}
//-->
</script>
And lastly, my PHP code.
PHP Code:
PHP Code:
<?php
include 'private/config.php';
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT UserName, Pass FROM user WHERE UserName=\"".$username."\" AND Pass=\"".$password."\"";
$connection = mysql_connect($host,$un,$pass) or die("no connection");
mysql_select_db($database) or die( "Unable to select database");
$result = mysql_query($query) or die ("query failed");
$num_rows = mysql_num_rows($result);
if($num_rows==1){
echo ("login successful");
} else {
echo ($username . $password);
}
mysql_close($connection);
?>
I appreciate that I'm practically passing the problem onto you guys, but I really need this done. Thanks alot for any help you can give