LanguagesCSSAjax and the Yahoo! Connection Manager

Ajax and the Yahoo! Connection Manager

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

The introduction of Ajax techniques to the web has spurred a series of JavaScript libraries designed to aid in cross-browser Ajax coding. A search for Ajax libraries on your favorite search engine will reveal a plethora of libraries claiming to be the best for such tasks. Recently, Yahoo! released some of its JavaScript utilities to the public; among them is the Connection Manager.

With Ajax making heavy use of XMLHttp, many developers are looking for ways to equalize the differences between browser implementations. The Yahoo! Connection Manager does this by handling all of the processing behind the scenes, exposing a simple API that frees developers from cross-browser concerns.

Before beginning, make sure you read the Yahoo! license agreement for JavaScript components at http://developer.yahoo.net/yui/license.txt. It’s a standard BSD-style license, but you should be sure to read it over anyway. You can download the Connect Managed code from http://developer.yahoo.net/yui/connection/index.html#download. The code download includes the source code as well as documentation, but no examples.

Setup

There are two JavaScript files necessary to use the Connection Manager: YAHOO.js, which sets up the YAHOO namespace (this file is used by all the Yahoo! JavaScript components), and connection.js, which contains the XMLHttp code. The files must be included in this order as well:

<script type="text/javascript" src="/js/YAHOO.js">
<script type="text/javascript" src="/js/connection.js">

With these files included in your page, you are now ready to begin using the Connection Manager.

Basic Requests

The Yahoo! Connection Manager uses a different methodology than you may be used to for sending XMLHttp requests. Instead of creating objects, the Connection Manager exposes several static methods to handle requests. The method you’ll use most often is asyncRequest(), which has the following signature:

YAHOO.util.Connect.asyncRequest(request_type, url, callback, postdata);

The first argument, request_type, is the type of HTTP request to make: “get” or “post”. The second argument is simply the URL of the request. The third argument is a callback object containing methods to handle the response from the request. This object has the following basic form:

var callback = {
    success: function (oResponse) {
        //handle a successful response
    },
    failure: function (oResponse) {
        //handle an unsuccessful request
    }
}

As you can see, this object has two methods: success() and failure(). The former gets called when a response is returned as expected; the latter is called when an error occurs during the request. Essentially, anytime the request doesn’t return a status of 200, the failure() method is called. The argument that is passed in to both methods is a response object containing all of the information about the response (including all XMLHttp properties such as status, statusText, responseText, responseXML, etc.).

The final argument of asyncRequest() is the data to post to the server. For POST requests, this value is a string of URL-encoded values to be sent; for GET requests, this value can either be omitted or set to null.

Advanced Callback Objects

The callback object isn’t limited to just two methods, there are a couple other properties provided for ease of use. The first is the argument property, which you can use to pass an argument into the request so it will be returned in the response object. Note that this value is never sent to the server, it is only used for passing data around on the client. You can specify an type of value you want for this property:


var callback = {
    success: function (oResponse) {
        
        //retrieve the argument
        var sArg = oResponse.argument;

    },
    failure: function (oResponse) {

        //retrieve the argument
        var sArg = oResponse.argument;

    },

    argument: "string of info"
}

Once the argument property is defined, it will be returned on the response object that is passed into both the success() and failure() methods. The argument property on the response object contains this value.

There may be a case when you want the success() and failure() methods to call methods on another object. To ease this case, you can use the scope property to set the object scope of methods. For instance, suppose you have an object oObject that has the methods handleSuccess() and handleFailure() that you want to use for success() and failure(), respectively. If you were just to pass in pointers to those methods, you would lose the scope in which they are to be executed (i.e., the this object inside of these methods would not refer to oObject). But, by setting the scope property, you can maintain the proper scope for these methods:

var callback = {
    success: oObject.handleSuccess,
    failure: oObject.handleFailure,
    scope: oObject
}

Monitoring and Managing Requests

One of the limitations of XMLHttp is the lack of a built-in method to monitor and manage multiple requests. The Yahoo! Connection Manager has implemented features that allow you to determine if a request is still pending as well as the ability to abort a request that has not yet completed.

The asyncRequest() method actually returns an object representing the request that was just made. This object can be used later to determine if the request is still pending by passing it to the isCallInProgress() method, like so:

var oConnect = YAHOO.util.Connect.asyncRequest("get", 
	"info.htm", oCallback, null);
alert(YAHOO.util.Connect.isCallInProgress(oConnect)); 
	//outputs "true"

Using this method, you can determine if a particular request has been completed or not. There may even be a time when you have decided that even though the call hasn’t completed, you don’t want to continue the request. At that time, you can use the abort() method, passing in the same object:

var oConnect = 
YAHOO.util.Connect.asyncRequest("get", 
	"info.htm", oCallback, null);
if(YAHOO.util.Connect.isCallInProgress(oConnect)) {
    YAHOO.util.Connect.abort(oConnect);
}

Calling abort() stops the current request and frees the resources associated with it.

Form Interaction

It is becoming more and more common to submit form values through an Ajax request instead of using the traditional form posting technique. The Yahoo! Connection Manager makes this easy by allowing you to set a form whose data should be sent through the request. For instance, suppose you have a form with the ID of “frmInfo”. You could set up a POST request to submit the data contained in the form like so:

var oForm = document.getElementById("frmInfo");
YAHOO.util.Connect.setForm(oForm);
YAHOO.util.Connect.asyncRequest("post", "datahandler.php", oCallback);

Using the setForm() method, the Connection Manager creates a string of data to be send in the next request. Because of this, there is no need to specify the fourth argument for the asyncRequest() method, since all the data is already retrieved from the form.

It’s important to note that the data string is constructed when you call setForm(), not when asyncRequest() is called. The data being sent is the data at the time when setForm() was called, so this method should only be called right before a call to asyncRequest(), to ensure that the data is the most recent available.

Additional Features

Presently, Internet Explorer uses ActiveX objects for XMLHttp. These ActiveX objects have string-based signatures that must be used to create the object using JavaScript. Since the Connection Manager handles this creation for you, generally you don’t need to know what these signatures are. However, if a change to the signatures occurs in the future, you can specify the most recent signature by using setProgId() like so:

YAHOO.util.Connect.setProgId("some.future.ActiveX.signature");

Here, the Connection Manager will attempt to create an ActiveX object with the signature “some.future.ActiveX.signature” before it attempts to create an object from the known list of signatures. This is something that Yahoo! provided to future-proof the library (though Internet Explorer 7 will feature a native XMLHttpRequest object as other browsers now do; this may not be necessary). Unlike other methods, this method sets the signature string for all requests.

You can also send header information by using the initHeader() method, such as:


YAHOO.util.Connect.initHeader("MyName", "Nicholas");
YAHOO.util.Connect.asyncRequest("get", "info.php", oCallback);

In this example, an extra header with a name of “MyName” and a value of “Nicholas” is sent to the server. Note that this header is only good for one request; all headers reset to default values after each request.

There’s no need to set the “Content-type” header for POST requests. The Connection Manager handles this for you behind the scenes.

Limitations

While the Yahoo! Connection Manager does make some requests easier, it does have its limitations. Currently, only asynchronous requests are supported, so you’ll be stuck using old school XMLHttp is you need to make a synchronous request. Though many argue that synchronous requests should never be used, sometimes there are practical reasons for it.

It is also worth noting that this is version 0.9 of the Connection Manager, so undoubtedly there will be some additions and changes in the future. However, for the time being, it remains one of the most compact libraries for cross-browser XMLHttp available.

About the Author

Nicholas C. Zakas is the author of Professional Ajax by (Wiley Press, ISBN: 0-471-77778-1) and Professional JavaScript for Web Developers (Wiley Press, ISBN: 0-7645-7908-8).

Adapted from Professional Ajax written by Nicolas C. Zakas . Copyright 2006 by Wiley Publishing, Inc. All rights reserved. Reproduced here by permission of the
publisher.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories