Adding Ajax with jQuery

March 29, 2009
This entry is part 6 of 7 in the series Introduction to jQuery

In this, the somewhat delayed Part 6 of my series on the jQuery JavaScript framework, I talk about performing Ajax requests using jQuery. You may want to read the previous five parts before getting into this one:

  1. [intlink id=”110″ type=”post”]Incorporating jQuery into an HTML page[/intlink]
  2. [intlink id=”248″ type=”post”]Selecting page elements[/intlink]
  3. [intlink id=”261″ type=”post”]Adding event handlers[/intlink]
  4. [intlink id=”298″ type=”post”]Applying effects[/intlink]
  5. [intlink id=”300″ type=”post”]Manipulating elements[/intlink]

Ajax, which may or may not stand for Asynchronous JavaScript and XML, depending upon whom you ask, is largely responsible for JavaScript’s current status. What was once a “toy” language used for rollover images at best, and annoying distractions at worst, is now a viable tool for developing Rich Internet Applications. The ability to make server-side requests behind-the-scenes so that user never has to leave the current page has transformed Web applications into more responsive, dynamic experiences, much more similar to what the user’s come to expect from their desktop applications (the expansion and adoption of broadband access is also a factor, among others). But this post isn’t intended to convince you to use Ajax, rather to show you how easily you can use it with jQuery. Because everything’s easier with jQuery!

There are a couple of different ways you can make Ajax requests using jQuery. To start, there’s the load() method. This method makes a request of a specific server-side resource and uses the returned result as the content for the element to which it’s applied. For example, say you have a DIV with an ID of news. You could load the current news, returned by a server-side script, into that DIV by doing this: $(‘#news’).load(‘fetch_news.php’). In this example, the PHP script presumably just returns a bunch of text, which is then used as the innerHTML value for the selected element. You can pass GET values to the server-side script by appending them to the URL, or pass POST values by providing a second argument containing the data to be posted. If you check out the jQuery documentation for load(), you’ll see an example where part of the returned text is parsed out and used.

If you want to do something more dynamic with the returned response, you can use the aptly named get() and post() methods.Unlike a lot of the methods I’ve discussed in my posts thus far, these methods aren’t applied to specific elements. Instead, the syntax you’ll see are $.get() and $.post(). Any method that gets called like $.methodName() are utility methods, as they apply to the document as a whole, and not to any subset of the DOM.

The get() method takes up to four arguments: a URL, optional parameters (data to be sent to the server), a function to be called when the request is completed, and the type of response to expect. For this fourth argument, use a string: text, html, xml, json, script, or jsonp. As an example, say you want to call the server-side script to see if a username is available:

$.get('check_username.php', { username: 'test' }, 
    function(data) { 
        alert (data); 
    }, 
'text');

So that makes a request to check_username.php, found in the same directory on the server as this current page. The request sends along a value of test assigned to username (so the PHP script would refer to $_GET[‘username’]). The anonymous function will be called when the request is completed. It receives one argument, the returned response, assigned to data, which is then alerted. Finally, we state that text is expected back. That { username: ‘test’ } structure may seem a little strange. This is just one way of creating an object in JavaScript. In this case, it’s an anonymous object with one property (username). To pass multiple values, you would separate each by a comma: { username: ‘test’, color: ‘blue’, timezone: ‘EST’ }. Do note that the properties themselves are not quoted but their values are. Also, the anonymous function can be written to take two arguments, the second being a text version of the returned status, like success or notmodified.

In context, where you might check a provided username after the corresponding form field has changed, you would do this:

 // Call this anonymous function when the input's value changes:
$('#usernameInput').change(function() {

    // Create a new, empty object.
    var data = new Object();

    // Add a property called 'username' with a value of the form input's value:
    data.username = $('#usernameInput').val();

    $.get('check_username.php', data, function(response) { alert (response); }, 'text');

});

(In a more complete example, though, you would confirm that the input has some value before making the request, and then probably do some error reporting based upon the result. Like if the result was a simple binary value for available/unavailable, you could add a message to the DOM or change the class of the form input’s label to indicate the unavailability of the username.)

The post() method is used exactly like get(), but makes a POST request. Generally speaking, you should make GET requests when you’re just fetching data from a page; you use POST when the intention is to alter content on the server. For comparison, normal viewing of a page in the browser, or clicking on a link, is a GET request; submitting a form is often a POST request, where the result of that request is something dynamic happening, like updating a record in a database or sending an email.

The primary Ajax-related jQuery method is…ajax()! Like get() and post(), ajax() is not invoked on a selected element. This method only takes one argument, which is an object of options. You can find the full list of options in jQuery’s manual, but the key ones are: data, dataType, success, type, and url. The data is the data to be sent, as an object (like in the above get() example). The dataType option is the same as the fourth argument to get() and post(), with a value like text, html, json, jsonp, script, or xml. The value assigned to success is the function to be called when the request succeeds. The type is either get or post. The url value is the server-side script to which the request should be made.

Fleshing out the earlier get() example using ajax(), you’d have something like this:

// Call this anonymous function when the input's value changes:
$('#usernameInput').change(function() {

    // Create the data to be sent along as an object:
    var data = new Object();
    data.username = $('#usernameInput').val();

    // Create the Ajax options as an object:
    var options = new Object();
    options.data = data;
    options.dataType = 'text';
    options.type = 'get';
    options.success = function(response) {
        if (response == 1) { // Good!
            // Add a message:
            $('#usernameInputMsg').text('The username is available.');

            // Remove the error class, if present:
            $('#usernameInputLabel, #usernameInputMsg').removeClass('error');

        } else if (response == 0) { // Bad!
            // Add a message:
            $('#usernameInputMsg').text('The username is unavailable!');

            // Add the error class to two elements:
            $('#usernameInputLabel, #usernameInputMsg').addClass('error'); // 
        }
    };
    options.url = 'check_username.php';

    $.ajax(options); // Make the request!

});

You can see this in action here. Note that for creating the both objects used in the request, I’m doing a longer, more formal object creation, to make it more clear what’s going on. There are more terse ways of accomplishing the same thing.

And that’s it for Ajax in jQuery. As always, there’s more information in the jQuery manual and in various tutorials online. And in my next post, I’ll discuss plug-ins, among them is the Form plug-in, which provides an easy way to submit form data via Ajax.