ajax and yahoo
TRANSCRIPT
-
8/3/2019 Ajax and Yahoo
1/4
Ajax and the Yahoo! Connection Manager
By Nicholas C. Zakas
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 oflibraries claiming to be the best for such tasks. Recently, Yahoo! released some of its JavaScript utilities tothe public; among them is the Connection Manager.
With Ajax making heavy use of XMLHttp, many developers are looking for ways to equalize the differencesbetween browser implementations. The Yahoo! Connection Manager does this by handling all of theprocessing 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 athttp://developer.yahoo.net/yui/license.txt. It's a standard BSD-style license, but you should be sure to read itover anyway. You can download the Connect Managed code fromhttp://developer.yahoo.net/yui/connection/index.html#download. The code download includes the sourcecode 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:
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 sendingXMLHttp 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 argumentis simply the URL of the request. The third argument is a callback object containing methods to handle theresponse 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
http://www.wrox.com/WileyCDA/Section/id-291289.htmlhttp://developer.yahoo.net/yui/license.txthttp://developer.yahoo.net/yui/connection/index.html#downloadhttp://developer.yahoo.net/yui/connection/index.html#downloadhttp://developer.yahoo.net/yui/license.txthttp://www.wrox.com/WileyCDA/Section/id-291289.html -
8/3/2019 Ajax and Yahoo
2/4
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 passingdata 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
-
8/3/2019 Ajax and Yahoo
3/4
}
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 stillpending 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 bea 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 thetraditional form posting technique. The Yahoo! Connection Manager makes this easy by allowing you to seta 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
-
8/3/2019 Ajax and Yahoo
4/4
Presently, Internet Explorer uses ActiveX objects for XMLHttp. These ActiveX objects have string-basedsignatures that must be used to create the object using JavaScript. Since the Connection Manager handlesthis 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. Thisis something that Yahoo! provided to future-proof the library (though Internet Explorer 7 will feature a native
XMLHttpRequestobject 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. TheConnection 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 youneed to make a synchronous request. Though many argue that synchronous requests should never beused, 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 someadditions and changes in the future. However, for the time being, it remains one of the most compactlibraries for cross-browser XMLHttp available.
Nicholas C. Zakas is the lead author ofProfessional Ajaxby (Wrox, 2006, ISBN: 0-471-77778-1) and theauthor ofProfessional JavaScript for Web Developers(Wrox, 2005, ISBN: 0-7645-7908-8). He hasworked in web development for more than five years. He has helped develop web solutions in use at some
of the largest companies in the world. Nicholas is also an active blogger on JavaScript and Ajax topics athttp://www.nczonline.net/and his most recent other article at Wrox.com isXMLHttp Requests for Ajax.
http://www.wrox.com/WileyCDA/WroxTitle/productCd-0471777781.htmlhttp://www.wrox.com/WileyCDA/WroxTitle/productCd-0764579088.htmlhttp://www.nczonline.net/http://www.wrox.com/WileyCDA/Section/id-291289.htmlhttp://www.wrox.com/WileyCDA/Section/id-291289.htmlhttp://www.nczonline.net/http://www.wrox.com/WileyCDA/WroxTitle/productCd-0764579088.htmlhttp://www.wrox.com/WileyCDA/WroxTitle/productCd-0471777781.html