8 min read

As far as web interface design techniques are concerned, AJAX is definitely the way to go. The term AJAX has been part of the mainstream development community’s vocabulary since early 2005, yet AJAX reinvented existing technologies as something new and exciting, and paved the way to a better, more attractive, and interactive web (sometimes referred to loosely as web 2.0) where web applications feel much more like desktop applications.

The very first JavaScript libraries sprang into existence as a means of abstracting away the differences in AJAX implementation between platforms, thereby allowing developers to focus on the important things in web design instead of worrying about compatibility issues. The result in many cases is a quick and easy way for developers to cut down on the amount of code they are required to produce, and a better more interactive experience for end users and website visitors.

The Connection Manager—A Special Introduction

The Connection Manager utility is by no means the smallest, most light-weight component included with the YUI, but it’s certainly not the largest either, yet it packs so much functionality into just 12Kb (for the –min version).

Connection Manager provides a fast and reliable means of accessing server-side resources, such as PHP or ASP scripts and handling the response. A series of supporting objects manage the different stages of any asynchronous transactions, whilst providing additional functionality where necessary.

Connection is one of just a few of the utilities that are supported by a single class; this makes looking up its methods nice and straight-forward. It also doesn’t have any properties at all (although the objects that it creates all have their own members which hold various pieces of information), which makes using it even easier!

This utility is what is known as a singleton utility, which means that there can only be one live instance of the utility at any one time, differing from many of the other components of the library. Don’t worry though, this doesn’t restrict you to only making one request; Connection will manage as many separate requests as you need.

Because this utility is a singleton, there are important considerations that advanced coders may want to take note of. Unlike some of the other library components, Connection cannot be subclassed—all of its class’s members are static, meaning that they won’t be picked up when using the YAHOO global .extend() method.

It wraps up the cross-browser creation of the XMLHttpRequest (XHR) object, as well as a simple to use object-based method of accessing the server response and any associated data, into a simple package which handles the request from start to finish. This requires minimal input from you, the developer, saving time as well as effort.

Another object created by Connection is the response object, which is created once the transaction has completed. The response object gives you access via its members to a rich set of data including the id of the transaction, the HTTP status code and status message, and either the responseText and responseXML members depending on the format of the data returned.

Like most of the other library components, Connection Manager provides a series of global custom events that can be used to hook into key moments during any transaction. We’ll look at these events in more detail later on in the article but rest assured, there are events marking the start and completion of transactions, as well as success, failure, and abort events.

The Connection utility has been a part of the YUI since its second public release (the 0.9.0 release) and has seen considerable bug fixing and refinement since this time. This makes it one of the more reliable and better documented utilities available.

Connection is such a useful utility that it’s used by several other library components in order to obtain data from remote sources. Other components that make use of Connection Manager include the AutoComplete control, DataTable, DataSource, and Tabview.

It is one of the only library components not dependant on the DOM utility. All it requires are the YAHOO global utility and the Event utility. That doesn’t mean that you can’t include a reference to the DOM utility, however, to make use of its excellent DOM manipulation convenience methods.

The XMLHttpRequest Object Interface

When working with the Connection utility you’ll never be required to manually create or access an XHR object directly. Instead, you talk to the utility and this works with the object for you using whichever code is appropriate for the browser in use. This means that you don’t need separate methods of creating an XHR object in order to keep each browser happy.

A transaction describes the complete process of making a request to the server and receiving and processing the response. Connection Manager handles transactions from beginning to end, providing different services at different points during a request.

Transactions are initiated using the .asyncRequest() method which acts as a constructor for the connection object. The method takes several arguments: the first specifies the HTTP method that the transaction should use, the second specifies the URL of your server-side script while the third allows you to add a reference to a callback object.

A fourth, optional, argument can also be used to specify a POST message if the HTTP method is set to use POST giving you an easy means of sending data to the server as well as retrieving it. This is rarely required however, even when using the POST method, as we shall see later in the article.

It’s also very easy to build in query string parameters if these are required to obtain the data that you are making the request for. It can be hard coded into a variable and then passed in as the second argument of the Connection constructor instead of setting the second argument manually within the constructor.

Connection Manager takes these arguments and uses them to set up the XHR object that will be used for the transaction on your behalf. Once this has been done, and Connection has made the request, you then need to define a new object yourself that will allow you to react to a range of responses from the server.

A Closer Look at the Response Object

I briefly mentioned the response object that is created by the utility automatically once a transaction has completed, let’s now take a slightly more in-depth view at this object. It will be created after any transaction, whether or not it was considered a success.

The callback functions you define to handle successful or failed transactions (which we’ll examine in more detail very shortly) are automatically passed to the response object as an argument. Accessing it is extremely easy and requires no additional intervention from yourself.

If the transaction fails, this object gives you access to the HTTP failure code and HTTP status message which are received from the server. Examining these two members of the response object can highlight what happened to make the request fail, making it integral to any Connection implementation.

If the transaction was a success, these two members will still be populated but with a success code and status message, and additional members such as responseText or responseXML will also contain data for you to manipulate.

If you need to obtain the HTTP response headers sent by the server as part of the response, these can be obtained using either the getResponseHeader collection, or the getAllResponseHeaders member.

In the case of file uploads, some of these members will not be available via the response object. File uploads are the one type of transaction that do not make use of the XHR object at all, so the HTTP code and status message members cannot be used. Similarly, there will not be either a textual or XML-based response when uploading files.

Managing the Response with a Callback Object

In order to successfully negotiate the response from the server, a literal callback object should be defined which allows you to deal quickly and easily with the information returned whether it is a success, failure, or another category of response.

Each member of this object invokes a callback function or performs some other action relevant to your implementation. These members can be one of several types including another object, a function call or even a string or integer depending on the requirements of your application.

The most common members you would use in your callback object would usually be based upon success and failure function calls to handle these basic response types, with each member calling its associated function when a particular HTTP response code is received by the response object.

It’s also very easy to add an additional member to this object which allows you to include data which may be useful when processing the response form the server. In this situation, the argument object member can be used and can take a string, a number, an object, or an array.

Other optional members include a customevents handler to deal with custom, per-transaction events as opposed to the global events that are available to any and all transactions, a scope object used to set the scope of your handler functions, and a timeout count used to set the wait time before Connection aborts the transaction and assumes failure.

The remaining member of the callback object is the upload handler which is of course a special handler to deal specifically with file uploads. As I already mentioned, the response object will be missing success of failure details when dealing with file uploads, however, you can still define a callback function to be executed once the upload transaction has completed.

Subscribe to the weekly Packt Hub newsletter. We'll send you this year's Skill Up Developer Skills Report.

* indicates required


Please enter your comment!
Please enter your name here