Getting Started with AJAX in jQuery
By Akash Mehta2008-05-11
Putting it all together
Here's the completed code:
<!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>
<script type="text/javascript">
$(document).ready(function() {
$("#login_form").submit(function() {
var unameval = $("#username").val();
var pwordval = $("#password").val();
$.post("backend.php", { username: unameval,
password: pwordval }, function(data) {
$("#status p").html(data);
});
return false;
});
});
</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>
And the PHP backend code:
<?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>";
}
?>
Save these as index.html and backend.php in the same folder on a PHP-enabled web server to try them out. Make sure you download and save jquery.js from jQuery.com in the same folder as well. If you try to login with the username "test" and password "password", you should see a success message appear after a brief delay. Congratulations, you've just built your first AJAX-enabled web page with jQuery!
Tutorial Pages:
» Introduction to jQuery
» Building a simple AJAX login form
» The jQuery behaviours
» Putting it all together
» Further reading
