4.3. jQuery

The jQuery library (available at www.jquery.com) is another library that does much more than simply Ajax communication, but at its small size (15KB), the extra features can be helpful in some situations.

Unlike the previous two libraries discussed in this chapter, jQuery aims to change the way you write JavaScript. It uses a querying interface to find specific nodes in the web page. The basic expression language used by jQuery is a mix of CSS selectors (from CSS Levels 1–3) and simple XPath expressions. Using this mix, it's possible to find specific nodes or groups of nodes without manipulating the DOM directly.

4.3.1. Simple jQuery Expressions

Since jQuery relies to heavily on its querying system, it's important to first understand how it works. The function used to query the DOM is $(), which accepts a string argument containing an expression. The expression may match one or many nodes in the DOM document, and the return value is another jQuery object that can be used to manipulate the result set (you won't be receiving any arrays or DOM elements back from most jQuery methods). This allows you to chain together jQuery methods into long groups of actions. Here are some sample queries:

//get all <p> elements
$("p");

//get the <div> element with an ID of myDiv
$("div#myDiv");

//get all textboxes (all <input> elements with type attribute equal to "text")
$("input[@type=text]");

As mentioned previously, each of these calls returns another jQuery object that can be used to manipulate the result set. Here are the same queries with actions attached:

//get all <p> elements and hide them
$("p").hide();

//get the <div> element with an ID of myDiv and change its font to Arial
$("div#myDiv").css("font-family", "Arial");

//get all textboxes (all <input> elements with type attribute equal to "text")
//and set their width to 400 pixels
$("input[@type=text]").width("400px");

For each of these result sets, an action is now taking place. The first line hides all <p> elements on the page; the second changes the font of the <div> element with an ID of "myDiv"; the third sets the width of all textboxes to 400 pixels. Programming JavaScript in this manner takes some getting used to, but jQuery already has a pretty strong following among developers due to its simple interface.

NOTE

It's beyond the scope of this book to discuss all of the features of jQuery. Please visit www.jquery.com to learn more.

4.3.2. Executing GET Requests

There are several options for performing GET requests using jQuery. The simplest method is to use $.get(), which accepts a URL and a callback function as arguments. The callback function receives two arguments, the text sent back from the server and a status string ("success" or "error"), such as:

$.get("path/to/data.php?name=value", function (sData, sStatus) {
    alert(sStatus + ":" + sData);
});

It's also possible to pass in an associative array of name-value pairs to pass with the URL instead of specifically defining a query string:

$.get("path/to/data.php", { name: "value" }, function (sData, sStatus) {
    alert(sStatus + ":" + sData);
});

The properties of the associative array are encoded and added to the query string, taking this responsibility away from the developer.

There are also several specialized GET methods in jQuery, each designed for a different purpose:

  • $.getIfModified(): Performs a GET request only if the resource has been modified since the last time it was requested. Same arguments as $.get().

  • $.getJSON(): Performs a GET request and evaluates the JSON response into a JavaScript object. Same arguments as $.get() except the callback function receives a JavaScript object instead of text. JSON is discussed in Chapter 8.

  • $.getScript(): Performs a GET request and expects JavaScript code as a response. The code is executed upon response. Same arguments as $.get() except that the callback function doesn't receive any information.

Of course, it is up to your individual requirements as to which method is appropriate.

4.3.3. GET Example

By revisiting the first XHR example, you can see that jQuery can be used to simplify the code necessary to retrieve information from the server:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>jQuery GET Example</title>
    <script type="text/javascript"src="jquery.js"></script>
    <script type="text/javascript">
          //<![CDATA[
        function requestCustomerInfo() {
            var sId = $("input#txtCustomerId").val();
            $.get("GetCustomerData.php?id=" + sId, displayCustomerInfo);
        }

        function displayCustomerInfo(sText, sStatus) {
            if (sStatus == "success") {
                $("div#divCustomerInfo").html(sText);
            } else {
                $("div#divCustomerInfo").html("An error occurred.");
            }
        }
    //]]>
    </script>
</head>
<body>
    <p>Enter customer ID number to retrieve information:</p>
    <p>Customer ID: <input type="text" id="txtCustomerId" value="" /></p>
    <p><input type="button" value="Get Customer Info"
              onclick="requestCustomerInfo()" /></p>
    <div id="divCustomerInfo"></div>
</body>
</html>

All of the JavaScript code in this example has been changed to use jQuery, which drastically reduces the amount of code necessary to perform this operation. The value of the textbox is retrieved by the expression $("input#txtCustomerId").val() and stored in sId (the val() method retrieves the value of a form field). Next, the $.get() method is called, passing in displayCustomerInfo() as the callback function. Since callback functions receive only one argument, text back from the server, the displayCustomerInfo() method can be used directly as the callback. The function itself has also been changed to use jQuery in order to show the html() method, which gets or sets the HTML content of a given element or set of elements.

Using the $.get() method with an associative array of requestCustomerInfo() can be rewritten as:

function requestCustomerInfo() {
    var sId = $("input#txtCustomerId").val();
    $.get("GetCustomerData.php", { id : sId }, displayCustomerInfo);
}

This takes responsibility for properly formatting the query string out of the developer's hands, allowing jQuery to handle the encoding and formatting.

4.3.4. The $.post() Method

POST requests are sent in jQuery using the $.post() method. This method accepts the same arguments as $.get(): a URL, an associative array of parameters, and a callback function to receive the returned data. For example:

$.post("path/to/data.php", { name: "value" }, function (sData, sStatus) {
    alert(sStatus + ":" + sData);
});

As with GET requests, jQuery encodes the POST parameters in the associative array and sends that data as the request body.

Both the second and third arguments to $.post() are optional; however, there's no reason to send a POST without data (the second argument). It's also recommended that a callback function always be provided to monitor the status of the response.

4.3.5. POST Example

To illustrate using the $.post() method, recall the POST example using XHR from Chapter 2. In that example, it was necessary to serialize a form into a string. Since the $.post() method doesn't accept a string for data, the getRequestBody() function must be changed to create an associative array of data instead of a string:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>jQuery POST Example</title>
    <script type="text/javascript"src="jquery.js"></script>
    <script type="text/javascript">

//<![CDATA[
        function sendRequest() {
            var oForm = document.forms[0];
            var oBody = getRequestBody(oForm);
            $.post("SaveCustomer.php", oBody, saveResult);
        }

        function getRequestBody(oForm) {

            var oParams = {};

            for (var i=0 ; i < oForm.elements.length; i++) {
                var oField = oForm.elements[i];
                switch (oField.type) {

                    case "button":
                    case "submit":
                    case "reset":
                        break;

                    case "checkbox":
                    case "radio":
                        if (!oField.checked) {
                            break;
                        }

                    case "text":
                    case "hidden":
                    case "password":
                        oParams[oField.name] = oField.value;
                        break;

                    default:

                        switch(oField.tagName.toLowerCase()) {
                            case "select":
                                oParams[oField.name] =
                                        oField.options[oField.selectedIndex].value;
                                break;
                            default:
                                oParams[oField.name] = oField.value;
                        }
                }
            }

            return oParams;
        }

        function saveResult(sMessage, sStatus) {
            if (sStatus == "success") {
                $("div#divStatus").html("Request completed: " + sMessage);
            } else {
                $("div#divStatus").html("An error occurred.");

}
        }
    //]]>
    </script>
</head>
<body>
    <form method="post" action="SaveCustomer.php"
          onsubmit="sendRequest(); return false">
    <p>Enter customer information to be saved:</p>
    <p>Customer Name: <input type="text" name="txtName" value="" /><br />
    Address: <input type="text" name="txtAddress" value="" /><br />
    City: <input type="text" name="txtCity" value="" /><br />
    State: <input type="text" name="txtState" value="" /><br />
    Zip Code: <input type="text" name="txtZipCode" value="" /><br />
    Phone: <input type="text" name="txtPhone" value="" /><br />
    E-mail: <input type="text" name="txtEmail" value="" /></p>
    <p><input type="submit" value="Save Customer Info" /></p>
    </form>
    <div id="divStatus"></div>
</body>
</html>

The only other changes are to saveResult(), to use jQuery to access the divStatus element. There isn't a large amount of code savings for this particular example, but there are several other ways to initiate Ajax communication using jQuery.

4.3.6. The load() Method

The previous two examples simply fill an HTML element with the data returned from the server, which is a common Ajax pattern. The Prototype library provided Ajax.Updater to simplify this pattern; jQuery provides the load() method for the same purpose.

The load() method can be called on any element or group of elements in jQuery and has two modes: GET and POST. To use GET mode, provide a URL (with a query string) and an optional callback function; for POST, provide a URL, an associative array of values, and an optional callback function.

Changing the GET example to use load() really simplifies the JavaScript necessary to achieve the desired effect:

function requestCustomerInfo() {
    var sId = $("input#txtCustomerId").val();
    $("div#divCustomerInfo").load("GetCustomerData.php?id=" + sId);
}

The first step in this example is to get a reference to divCustomerInfo. Once that has been completed, the load() method is called with only a URL as an argument. The callback function isn't necessary here, since the default behavior is to place the returned data into the <div/>. It's also important to note that the displayCustomerInfo() function is no longer needed, reducing the amount of code dramatically.

In the POST example, it's also possible to reduce the amount of code by updating the sendRequest() function:

function sendRequest() {
    var oForm = document.forms[0];
    var oBody = getRequestBody(oForm);

    $("div#divStatus").load("SaveCustomer.php", oBody);
}

By changing just one line, it's possible to eliminate the saveResult() function completely. This code now gets a reference to divStatus and then calls load(). Since the second argument is an associative array (oBody), the load() method assumes the request is a POST. Once again, a callback function isn't necessary.

The load() method provides a quick way to load content into an element, though you do lose the ability to handle individual cases of success or failure. There is, however, another method that allows more fine-grained control over Ajax communication.

4.3.7. The $.ajax() Method

All of the other methods discussed in this section are high level, hiding a lot of the communication detail from developers. These methods all have one thing in common: under the covers, they all use the $.ajax() method to initiate and handle requests. This method provides more fine-grained control over requests and responses.

The $.ajax() method accepts a single argument, which is an associative array of options, not unlike Prototype's Ajax.Request constructor. This options object is made up of the following properties:

  • type: The type of request, either GET or POST.

  • url: The URL to request.

  • data: An encoded string of data. Used for POST requests only.

  • dataType: The type of data expected as a response: "script," "xml," "html," or "json." If "script" is specified, then the returned data is loaded as JavaScript into the page.

  • success(): A function to call when a successful response is received. A successful response is anything with a status of 2xx or 304. This function receives two arguments: the XHR object and a status string.

  • error(): A function to call when an error occurs. Anything that isn't considered a success is considered an error. This function receives two arguments: the XHR object and a status string.

  • complete(): A function to call when a response is received; called for both successful and unsuccessful responses. This function receives two arguments: the XHR object and a status string.

So to recreate the GET example using $.ajax(), the requestCustomerInfo() function is changed to the following:

function requestCustomerInfo() {

    var sId = $("input#txtCustomerId").val();

    $.ajax({
        type : "GET",
        url : "GetCustomerData.php?id=" + sId,
        success : function (oXHR, status) {
            $("div#divCustomerInfo").html(oXHR.responseText);
        },
        error : function (oXHR, status) {
            $("div#divCustomerInfo").html("An error occurred.");
        }
    });
}

Since this is a low-level operation in jQuery, the success() and error() functions must look at the XHR object for additional information about the request, including the returned data.

4.3.8. The ajaxStart() and ajaxStop() Methods

Prototype isn't the only library that has global event handlers for Ajax requests; jQuery supports similar functionality by using the ajaxStart() and ajaxStop() methods. The ajaxStart() method fires when there are no Ajax requests pending and one is started. Likewise, the ajaxStop() method is called when all Ajax requests have completed. Both methods accept a function that should be called when the event occurs.

The first step to using these methods is to retrieve a reference to an element. Then, the ajaxStart() and ajaxStop() methods can be called on that element. For instance, to use a <div/> element with an ID of divStatus, the following code can be used:

$("div#divStatus").ajaxStart(function () {
    $(this).html("Contacting the server...");
}).ajaxStop(function () {
    $(this).html("Response received.");
});

This code calls both methods on divStatus. Since the ajaxStart() and ajaxStop() methods return jQuery objects, the two can be chained together. Because it is divStatus itself that should be updated, the $(this) object is used inside the functions along with the html() method to set the status text.

4.3.9. Limitations

The jQuery library provides a very interesting interface not only for Ajax communication but also for JavaScript in general; this is also one of the limitations. Using jQuery means abandoning some of the more common methods of JavaScript programming, including DOM manipulation. The library makes you more dependent on itself, since many of the features are implemented only as methods of jQuery objects. Still, there are some powerful methods that can enable simple or complex Ajax communication.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset