///Getting Started with AJAX in jQuery

Getting Started with AJAX in jQuery

Introduction to jQuery

AJAX is probably the biggest thing you can add to your site; with AJAX, you can dramatically increase functionality, and give your end users more usable web applications. But AJAX is tricky to get started with – it usually requires very complex JavaScript knowledge. In this tutorial, I’ll show you how to get started with AJAX using the jQuery JavaScript framework.

This tutorial requires basic knowledge of HTML, and a decent grasp of CSS and JavaScript. You’ll need a copy of the jQuery framework; download it from jQuery.com. I’m using version 1.2.3, but these samples should work with any 1.x release.

jQuery is a simple yet powerful JavaScript framework that’s easy for all web developers to get started with. At its core, it provides a layer to simplifying common JavaScript tasks, from page manipulation to basic effects and even AJAX. It leverages existing knowledge by incorporating CSS and HTML concepts where possible, and doesn’t require significant JavaScript knowledge.

Internally, jQuery is just a JavaScript object. It provides all its functionality through pure JavaScript; if you’ve read our JavaScript tutorial, you’ll have no trouble at all. The jQuery code is a downloadable JavaScript file, which can then be included on your web pages just like any other JavaScript file. Insert a script tag in the head of your HTML and you’re all set to use jQuery.

jQuery actually provides its standard jQuery object under the name $ – the dollar symbol. For example, when we want to use the get() method on the jQuery object, we can call $.get(). $ is simply an alias for jQuery, the actual name of the object; the symbol just saves you a bit of typing. When referring to the actual jQuery function, you can use $() instead of jQuery(). There are really only two JavaScript concepts jQuery introduces that you may not be familiar with: factory functions, and method chaining.

Factory functions

When working with jQuery, often you’ll want to be working with something. For example, you might want to be working with a particular area of the page, or a particular section of an AJAX request response. We use the jQuery factory function to tell jQuery what to work with. Consider this example:

var domhandle = document.getElementById("somedivid");
doSomethingTo(domhandle);

This code snippet would find an element on the page with the id “somedivid” and tell the doSomethingTo() function to work on it. In jQuery, we would achive the same with this:

$("#somedivid").doSomething();

There are two things to note here – first, the factory function jQuery() (alised as $()) has been called and passed the ID of the DOM element; second, we call doSomething() directly. The first section is an example of jQuery selectors, which allow us to select elements on the page using standard CSS selectors. jQuery supports CSS 1-3, and a bit of XPath. You can easily select elements on the page without complex DOM calls using CSS selectors with jQuery. Once we have called the factory function, the jQuery object knows we are working with the element with the id “somedivid”, and will be working with this when we call the doSomething() method on the jQuery object.

Method chaining

Technically, the jQuery() factory function is returning us the jQuery object. The object’s methods we can call can also return the jQuery object. Recall that, within an object, you can refer to the current object as this. Now, you can also return values from within a function/method. So why not return this? That’s exactly what jQuery does.

When you select a DOM element in jQuery using the factory function – $() – jQuery internally remembers what you are working on. You can then call most of the methods on the jQuery object in succession, but because each method returns the actual jQuery object, you can keep calling them without using the factory function again. Consider this example:

$("#somedivid").doSomething();
$("#somedivid").doSomethingElse();
$("#somedivid").doSomethingElse();

In jQuery, this could be shortened to:

$("#somedivid").doSomething().doSomethingElse().doSomethingElse();

This is because, at the completion of each function, we return (no pun intended) to the jQuery object, and can continue. The exception is when want to use the factory function again to work on something else; then we need another call (typically another line of code). This is one of the strengths of jQuery; it can be very compact and succinct, saving you time and making your code more maintainable.

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.

The jQuery behaviours

Once we have our frontend and backend in place, we can begin to glue them together using jQuery.

Beginning with document.ready

There are a number of potential issues with any complex JavaScript on the web. One of them is page “readiness” – that is, whether or not the page is ready to be manipulated. This problem occurs when your JavaScript is executed before your page has finished loading; problems can easily occur when, for example, you attempt to manipulate a HTML node that does not yet exist. jQuery provides a simple solution, document.ready, which allows us to bind a function to be executed when the document object – representing the current page – is fully loaded. It is used as follows:

$(document).ready(function(){
    // Do something.
});

You will notice our use of a lambda function – a function defined without a name but within a scope. We also use the document object as the jQuery selector. In addition to CSS selectors, the jQuery factory function accepts objects and DOM node references. Here, we select the document object and bind our new function to be executed when the object is ready. We can put any valid JavaScript code where the “Do something.” comment is located.

Binding events

Once we are sure the page is ready, we then need to bind our events. Typically, if you wanted to do something when a form was executed with DHTML / JavaScript, we would insert an onsubmit value to the form tag:

<form method="post" onsubmit="javascript:do_something();">

In jQuery, however, we can (and should) bind to the form’s submit event programatically. jQuery provides the submit() method to bind to the submit event of an object. Referring back to our backend code, we know that our form has an ID of “login_form”, so we select that and bind a lambda function to the event:

$(document).ready(function(){
    $("#login_form").submit(function(){
        // Do something when the form is submitted.
    });
});

Bring in the AJAX!

Now that we’re ready to handle the form submission, we can finally have some fun with AJAX. jQuery provides the get() and post() methods for AJAX requests of the respective HTTP request methods; both function similarly. We want to use a POST request, so we’ll use post() for now.

post() functions as a normal method without a factory, so it can be called simply through jQuery.post() – or in this case, $.post(). It takes three arguments: first, the URL to make the POST request to; second, parameters to pass; and third, a callback lambda function to be executed when the AJAX request is completed. Both the second and third parameter are entirely optional. jQuery also allows you to leave out one or the other; it will still work out what you want to do.

So, if we want to make a simple POST request to our backend.php, all we need to do is this:

$.post("backend.php");

To pass it some parameters, we use JSON, JavaScript object notation. JSON is simply key: value pairs, seperated by commas and enclosed in curly braces. For example, to pass two parameters, username and password, with values “test” and “password”, we would do the following:

$.post("backend.php", { username: "test", password: "password" });

But wait – we don’t want to put in the actual values, we want to tell it to get the values from the user’s input. We achieve this with jQuery’s val() function, which allows us to programmaticaly fetch the value of a DOM element (in our case, form input fields). We can easily add this in:

var unameval = $("#username").val();
var pwordval = $("#password").val();
$.post("backend.php", { username: unameval, password: pwordval });

Once again, we use the CSS selectors for the username and password fields, #username and #password, and run them through the jQuery factory function before using the val() method to extract the value. We put both values into variables, and pass this to the post() function. Finally, we need to do something when we get the result. Since we have created the div with the id “status” and put a p tag inside it, we can put the result into the content within this p tag. We do this with the html() method.

A callback function is essentially a function that is defined and stored to be “called back” later. In our case, we want to create a function to handle the response from the server to our AJAX request. We can’t really wait for this to happen, so we define our status message code within the callback function and finish. The callback function for an AJAX request will receive one parameter, the body of the response from the server, although other information is available.

So, to create our callback function and put everything together we have the following code:

$(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;
	});
});

This callback function takes the data parameter, and then sets the content of the p inside the div with id “status”.

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!

Further reading

If you want to extend your jQuery skills, there are quite a few avenues to do so. First, check out the Tutorials; jQuery has one of the most comprehensive collections of tutorials available online. Next, have a read through the documentation, to explore new areas of the jQuery API – also check out visualjquery.com, which will help you navigate the documentation easily. Finally, there’s a good book that you might also find useful.

2010-05-25T21:57:56+00:00 May 11th, 2008|AJAX|0 Comments

About the Author:

Akash Mehta is a web solutions consultant and application developer. He regularly advises website owners and small business on their online challenges, while researching and writing on innovative uses of web-related technologies for the developer community. In his copious free time, he enjoys cycling and investigating creative accounting methods.

Leave A Comment