AJAX login using jQuery
June 17th, 2009
jQuery makes ajax requests really easy. Below is HTML and javascript using jQuery that functions as a simple user login form. Also included a PHP file for testing. Here is what the code below will look like in action, try the username: username and the password:password. TRY IT
HTML Form:
<html xmlns="http://www.w3.org/1999/xhtml">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax Login Example</title>
<script type="text/javascript" src="jquery-1.2.6.js"></script>
<script type="text/javascript" src="loginscript.js"></script>
<style type="text/css">
#loginform{
width: 250px;
height: 200px;
padding: 30px;
background: #ccc;
font-family: Arial, Helvetica, sans-serif;
color: #333;
}
#loginform h1{
font-size: 18px;
padding: 0px;
margin: 0 0 10px 0;
}
#loginform label input{
width: 250px;
display: block;
margin: 0 0 10px 0;
}
#loginform button{
width: 80px;
height: 20px;
}
#loginform #invalidmessage{
text-transform: uppercase;
color: #990000;
font-weight: bold;
}
</style>
</head>
<body>
<form id='loginform' action='#'>
<h1>AJAX LOGIN EXAMPLE</h1>
<label>username:
<input id='username' type='text' />
</label>
<label>password:
<input id='password' type='password' />
</label>
<input id='submit' type='submit' value='submit'/>
<input id='reset' type='reset' value='reset' />
</form>
</body>
</html>
Javascript that uses jQuery:
// JavaScript Document
$(document).ready(function()
{
/////////On form submit button click
$("#submit").click(function(e)
{
e.preventDefault();
///////hides buttons and adds loader graphic
$("#submit").css("visibility","hidden");
$("#reset").css("visibility","hidden");
$("#invalidmessage").remove();
$("<img src='ajax-loader.gif' />").css("position","relative").css("top","-15px").attr("id","loaderimg").appendTo( $('#loginform') );
$.ajax({
type: "POST",
url: "checklogin.php",
data: "username=" + $("#username").val() + "&password=" + $("#password").val(),
success: function(response)
{
///////shows buttons again and removes loader graphic
$("#submit").css("visibility","visible");
$("#reset").css("visibility","visible");
$('#loaderimg').remove();
if(response == "1")
{
///////successful login
$("<p>you are logged in as: " + $("#username").val() + "</p>").attr("id","invalidmessage").appendTo($('#loginform') );
}else{
///////invalid login
$("<p>invalid login, try again</p>").attr("id","invalidmessage").appendTo($('#loginform') );
}
}
});
});
});
PHP code you could use to test the Javascript.
<?php
if($_POST['username'] == "username" && $_POST['password'] == "password")
{
print "1";
}else{
print "0";
}
?>