Tallan's Technology Blog

Tallan's Top Technologists Share Their Thoughts on Today's Technology Challenges

jQuery Part 3: Advanced jQuery

Dylan Barrett

Introduction

Welcome to the third and final installment of the jQuery saga.  This post will cover some of the more advanced features of jQuery such as Ajax, utility functions and plugins.  Along the way I will give examples that show how to use the functionality.  I suggest that you read through the first two parts of my jQuery overview which cover the basics of jQuery before reading this post.

Ajax

In addition to all of the goodness that jQuery provides that we covered in previous posts, jQuery also enables developers to easily make Ajax calls to a server.  In this post we will cover a few of the different methods available for making asynchronous calls.

The first and simplest Ajax method that jQuery provides is the load() function.  This function can be called on a jQuery wrapped set of elements and allows you to make an Ajax call to a server and insert the Ajax response into the selected elements.  The function has the following signature:

  • load(url, [data], [complete])

where url is the url you want to send the Ajax request to, data is an optional key-value map that you can send as parameters with the request, and complete is an optional callback function that is called when the request completes.  This function is great if you just want to receive data from the server and display it directly to the user.  For example, let’s say you have a SELECT list containing a list of products.  When the user selects a product from the list you can use the id of the product to send a request to the server that returns the corresponding description for the given id.  Using the load() function of jQuery you can fill a DIV with the description.  Here is the html for the example:

...
<select id="products">
  <option value="">Select...</option>
  <option value="1">Toaster</option>
  <option value="2">Microwave</option>
  <option value="3">Stove</option>
</select>
<div id="description"></div>
...

And here is the JavaScript:

$(function() {
  $('#products').change(function () {
    if ($(this).val() != "") {
      $('#description').load('GetPageDescription.php', { 'productId' : $(this).val() });
    }
  });
});

The result of this code is that when the product dropdown is changed, an Ajax request will be made to the server passing the value of the selected option as the productId parameter.  jQuery will take care of inserting the description into the DIV when the response returns from the server.

If you want to do more that simply load the response from the server into a DOM element then jQuery providers two additional functions: jQuery.get() and jQuery.post().  Both of these functions have the same signature:

  • jQuery.get(url, [data], [complete], [datatype])
  • jQuery.get(url, [data], [complete], [datatype])

The first three parameters are exactly the same as the parameters for load().  The datatype parameter allows you to specify what data type you are expecting to receive from the server.  This can have values such as “html”, “xml”, “script”, “json” and “text”.  The main difference between these functions and the load() function is that these are not called on a jQuery wrapped set, but instead are standalone functions.  If you want to do something with the response from the server you will have to pass in a handler function for the complete parameter.

Finally, if you want very fine control of the Ajax call, jQuery provides the jQuery.ajax() function.  This function takes in a single parameter: an object containing key-value pairs that allow you to set specific options for the Ajax call.  In addition to the parameters used by the other Ajax functions, you can pass a parameter that specifies whether the request should be asynchronous or not, parameters that allow you to specify callback functions for different stages in the Ajax lifecycle, and many more.  Regardless of your required level of control, jQuery will provide you with tools that will make Ajax easy and accessible.

Utilities

jQuery provides many useful utility functions that allow you to perform common tasks easily.  A small subset of these functions follows:

  • jQuery.inArray(value, array)
  • jQuery.map(array, callback(element, index))
  • jQuery.parseJSON(json)
  • jQuery.trim(string)

The jQuery.inArray() function will allow you to check if a value is in an array.  It takes the value and the array as parameters and returns a number.  The number will be -1 if the value is not in the array, otherwise it will be the index of the value in the array.

The jQuery.map() function should be familiar to those who have worked with functional programming languages.  It will take an array and a function as a parameter and apply the function to each element in the array to return a new array of the results.  For example, if we wish to take an array of numbers and square them we can use the following code:

var numbers = [2,3,5,6];
var squares = $.map(numbers, function(element,index) {
  return element * element;
});

The squares array will contain the values: 4, 9, 25 and 36.

The jQuery.parseJSON() function is especially useful when using the Ajax functionality.  The server may return a JSON string in the response.  In that case you can pass the JSON string to this function.  The function will parse the string and return a JavaScript object.

Finally, the jQuery.trim() function allows you to trim all whitespace off of the beginning and end of a string.  Simply pass the string to the function and it will return the trimmed string.

As you can see, the jQuery utility functions are very helpful.  While they are not as significant as the rest of jQuery’s features, they certainly do contribute to making JavaScript easier to use.

Plugins

The ability to extend jQuery with plugins may be one of its most important features.  The core of jQuery provides a strong foundation for your JavaScript code, so it is only natural that you may want to tie additional functionality to jQuery’s existing functionality.  In addition to creating your own jQuery plugins, you also can go to http://plugins.jquery.com to get access to hundreds of existing plugins that have been created.  If you can think of a problem, chances are that somebody has already created a plugin to help get around it.  Two useful jQuery plugins are the jQuery Validation plugin and the jQuery UI plugin.

The jQuery Validation plugin makes doing client-side validation easy!  In fact, Microsoft has chosen to use both jQuery and jQuery Validation by default in their latest version of ASP.NET.  Utilizing jQuery Validation in an ASP.NET MVC 3 is as easy as turning on client-side validation in the web.config (which is on by default) and setting some data annotation attributes on your model classes.  jQuery Validation contains many useful validation constraints.  For example, you can easily check to make sure that the user input is a valid email address or credit card number.  jQuery Validation has built in error messages that are displayed to the user when there is a problem.  The error messages can easily be customized.

The jQuery UI plugin is another very useful jQuery plugin that is available.  It makes doing tasks such as making your DOM elements draggable or resizable trivial.  For example, if you have a div with an id of “box” that you want to be able to drag around, simply do the following:

$('#box').draggable();

That’s it!  Your box is now draggable.  In addition to easily adding behaviors, you can also you jQuery UI to create cool widgets.  For example, jQuery UI comes with a great date picker widget.  If you have a textbox with id “postDate” that you want to use for dates, simply do the following:

$('#postDate').datepicker();

This will cause a calendar widget to appear on the screen below the textbox whenever the textbox receives focus.  Very useful!

Another cool widget that you can use it the dialog widget.  With the dialog widget you can turn any div into a dialog that pops up on the screen.  You can easily customize the appearance and behavior of the dialog, and even make it a modal dialog, a dialog that causes the rest of the page behind it to become grayed out and inaccessible until the dialog is closed.  This is just the tip of the iceberg when it comes to jQuery plugins.  I strongly encourage you to check out the jQuery Plugins page to see what else is available.

Conclusion

We have finally reached the end of our jQuery journey.  I hope you were able to learn about some of the amazing features that have made jQuery the most popular JavaScript library in use today.  In this article we covered some of the more advanced jQuery features such as its Ajax support, utilities, and its huge library of plugins.  At this time I encourage you to dive into jQuery.  Read some tutorials on the jQuery website, pick up a book, and start using jQuery in your own code today!  You may even contribute to the jQuery community by creating your own plugin and sharing it on the jQuery website.

Want to learn more?

As I mentioned in the first two parts of this series, two great resources for learning jQuery are the jQuery website at http://jquery.com as well as the book jQuery in Action by Bear Bibeault and Yehuda Katz, which I highly recommend.  I hope you enjoyed this article!

-Dylan

Tags: JavaScript, jQuery,

No comments

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

\\\