Getting Started with AJAX in jQuery
By Akash Mehta2008-05-11
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".
Tutorial Pages:
» Introduction to jQuery
» Building a simple AJAX login form
» The jQuery behaviours
» Putting it all together
» Further reading
