Getting Started with AJAX in jQuery
By Akash Mehta2008-05-11
Building a simple AJAX login form
We're going to use a simple AJAX login form to demonstrate the AJAX functionality in jQuery. We'll have a basic frontend HTML page, with some inline JavaScript, and a mock backend PHP script to check the login credentials. The PHP script will only check that the username is "test" and the password is "password"; when building your own systems, you can integrate them into your existing backend APIs.
The frontend
When building the front-end for a jQuery-enabled web application, there's only one thing you have to remember: id's. Most HTML elements can have ID attributes. If you want to be able to find them in jQuery, use IDs; essentially, to add behaviour through JavaScript, do what you would normally do to add style through CSS. This usually involves IDs on container div/spans, or classes on elements.
We won't cover actually putting together the HTML here, so that we can skip ahead to the JavaScript. The actual HTML is rather simple:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<form id="login_form" method="post">
<p>Username: <input type="text" id="username" /></p>
<p>Password: <input type="password" id="password" /></p>
<p><input type="submit" value="Login" /></p>
</form>
<div id="status">
<p></p>
</div>
</body>
</html>
Nothing special; just some usual HTML. We use a script tag to include the jQuery library. We'll need to do this on every page we want to use jQuery. Once this is in the head, we're all set to use jQuery.
The backend
The backend is equally simple; I've built this in PHP, but you could do it in ASP, JSP, Python, Perl; essentially, anything that accepts a standard HTTP connection. Here, I'm using a HTTP POST request with the data variables "username" and "password", but you can easily change this later, and alter the jQuery code to suit your needs.
Copy this into a file called "backend.php":
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if ($username == "test" && $password == "password")
{
print "<strong>Login succeeded!</strong>";
}
else
{
print "<strong>Login failed! Please try again.</strong>";
}
?>
A very simple and straightforward script; check if the POST variables "username" and "password" have the values "test" and "password" respectively, and output a snippet of HTML depending on the case.
Tutorial Pages:
» Introduction to jQuery
» Building a simple AJAX login form
» The jQuery behaviours
» Putting it all together
» Further reading
