YUI recommends YUI3.
YUI 2 has been deprecated since 2011. This site acts as an archive for files and documentation.
This documentation is no longer maintained.
Connection Manager is a utility that enables you to make in-page HTTP requests through a simplified interface to the XMLHttpRequest object. XMLHttpRequest is the mechanism commonly referred to as "Ajax," allowing your scripts to communicate with the server without a page reload, persisting the user interface across many client-server interactions. Connection Manager handles cross-browser instantiation of XMLHttpRequest, negotiates the server response and uses a callback pattern to process the response data.
To use Connection Manager, include the source file and its dependency in your web page with the script tag:
<!-- Dependency --> <script src="http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js"></script> <!-- Used for Custom Events and event listener bindings --> <script src="http://yui.yahooapis.com/2.9.0/build/event/event-min.js"></script> <!-- Source file --> <!-- If you require only basic HTTP transaction support, use the connection_core.js file. --> <script src="http://yui.yahooapis.com/2.9.0/build/connection/connection_core-min.js"></script> <!-- Use the full connection.js if you require the following features: - Form serialization. - File Upload using the iframe transport. - Cross-domain(XDR) transactions. --> <script src="http://yui.yahooapis.com/2.9.0/build/connection/connection-min.js"></script>
<!-- Dependency --> <script src="http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js"></script> <!-- Used for Custom Events and event listener bindings --> <script src="http://yui.yahooapis.com/2.9.0/build/event/event-min.js"></script> <!-- Source file --> <!-- If you require only basic HTTP transaction support, use the connection_core.js file. --> <script src="http://yui.yahooapis.com/2.9.0/build/connection/connection_core-min.js"></script> <!-- Use the full connection.js if you require the following features: - Form serialization. - File Upload using the iframe transport. - Cross-domain(XDR) transactions. --> <script src="http://yui.yahooapis.com/2.9.0/build/connection/connection-min.js"></script>
Instead of copying and pasting the filepaths above, try letting the YUI dependency Configurator determine the optimal file list for your desired components; the Configurator uses YUI Loader to write out the full HTML for including the precise files you need for your implementation.
Note: If you wish to include this component via the YUI Loader, its module name is connection
. (Click here for the full list of module names for YUI Loader.)
Where these files come from: The files included using the text above will be served from Yahoo! servers. JavaScript files are minified, meaning that comments and white space have been removed to make them more efficient to download. To use the full, commented versions or the -debug
versions of YUI JavaScript files, please download the library distribution and host the files on your own server.
Order matters: As is the case generally with JavaScript and CSS, order matters; these files should be included in the order specified above. If you include files in the wrong order, errors may result.
The following simple example initiates an asynchronous transaction using the Connection Manager utility.
var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback, null);
var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback, null);
In this code:
This section describes several common uses of the Connection Manager. It contains these subsections:
In an asynchronous transaction, you create a callback object to handle the server response and its associated data. You may omit the callback object if you don't care what information comes back from the server; all of the callback object's members are optional. However, in most cases you should supply at least three members in your callback object:
When reconciling a transaction, Connection Manager will evaluate the HTTP code returned by the server to
determine if the request was successful and will then call the appropriate callback handler (success
or failure
). You can also define the callback object's argument
member to pass an
argument or collection of arguments to both the success
and failure
handler.
/* * This is an example callback object with success * and failure members defined inline. The argument * property demonstrates how to pass multiple values * to the callback as an array. */ var callback = { success: function(o) {/*success handler code*/}, failure: function(o) {/*failure handler code*/}, argument: [argument1, argument2, argument3] };
/* * This is an example callback object with success * and failure members defined inline. The argument * property demonstrates how to pass multiple values * to the callback as an array. */ var callback = { success: function(o) {/*success handler code*/}, failure: function(o) {/*failure handler code*/}, argument: [argument1, argument2, argument3] };
The example that follows shows in more detail how to construct
a callback object with two members: success and failure, to handle the server
response. In this example, the success
and failure
members
are defined by the responseSuccess
and responseFailure
functions respectively.
These handler functions accept the response object o
from
Connection Manager.
// Passing an example of array of arguments to both // the success and failure callback handlers. var args = ['foo','bar']; var responseSuccess = function(o) { /* Please see the Success Case section for more * details on the response object's properties. * o.tId * o.status * o.statusText * o.getResponseHeader[ ] * o.getAllResponseHeaders * o.responseText * o.responseXML * o.argument */ }; var responseFailure = function(o) { // Access the response object's properties in the // same manner as listed in responseSuccess( ). // Please see the Failure Case section and // Communication Error sub-section for more details on the // response object's properties. }; var callback = { success:responseSuccess, failure:responseFailure, argument:args };
// Passing an example of array of arguments to both // the success and failure callback handlers. var args = ['foo','bar']; var responseSuccess = function(o) { /* Please see the Success Case section for more * details on the response object's properties. * o.tId * o.status * o.statusText * o.getResponseHeader[ ] * o.getAllResponseHeaders * o.responseText * o.responseXML * o.argument */ }; var responseFailure = function(o) { // Access the response object's properties in the // same manner as listed in responseSuccess( ). // Please see the Failure Case section and // Communication Error sub-section for more details on the // response object's properties. }; var callback = { success:responseSuccess, failure:responseFailure, argument:args };
Connection Manager can append a timestamp parameter to an HTTP GET request querystring, configured through the
callback object, to override the caching behavior of HTTP GET. This will produce a key-value of rnd=
timestamp
in the querystring. NOTE: By using this feature, HTTP GET requests become non-idempotent and
and the presence of this key-value in the querystring may produce side effects. Additionally, Web servers/
services can respond with the appropriate HTTP responses headers to prevent the resource from being cached.
/* * Set callback.cache to false to override HTTP GET caching. * A key-value of rnd=timestamp will be added to the * querystring. */ var callback = { cache:false };
/* * Set callback.cache to false to override HTTP GET caching. * A key-value of rnd=timestamp will be added to the * querystring. */ var callback = { cache:false };
When uploading files using YAHOO.util.Connect.setForm
, the callback object will require an
upload
handler instead of
success
and, or failure
handlers. (A transaction timeout will still use the failure
handler.) For more details, please see Upload Case and Forms and File
Upload.
/* * This is an example callback object with upload * and argument members defined inline. The argument * property demonstrates how to pass multiple values * to the upload handler as an array. */ var callback = { upload: function(o) {/*upload handler code*/}, argument: [argument1, argument2, argument3] };
/* * This is an example callback object with upload * and argument members defined inline. The argument * property demonstrates how to pass multiple values * to the upload handler as an array. */ var callback = { upload: function(o) {/*upload handler code*/}, argument: [argument1, argument2, argument3] };
When an object's method is used as the success or failure handler in a
callback, any usage of the this
keyword in
the method loses scope. While this can be partially resolved by passing a
reference to the handler's parent object as a user-defined argument, it still
invalidates the use of this
within the handler itself. To use
an object's method as a callback handler and maintain scope within the member,
define the callback member scope
with a value of this
.
/* * AjaxObject is a hypothetical object that encapsulates the transaction * request and callback logic. * * handleSuccess( ) provides success case logic * handleFailure( ) provides failure case logic * processResult( ) displays the results of the response from both the * success and failure handlers * call( ) calling this member starts the transaction request. */ var AjaxObject = { handleSuccess:function(o) { // This member handles the success response // and passes the response object o to AjaxObject's // processResult member. this.processResult(o); }, handleFailure:function(o) { // Failure handler }, processResult:function(o) { // This member is called by handleSuccess }, startRequest:function() { YAHOO.util.Connect.asyncRequest('POST', 'php/post.php', callback, "new=1&old=2"); } }; /* * Define the callback object for success and failure * handlers as well as object scope. */ var callback = { success:AjaxObject.handleSuccess, failure:AjaxObject.handleFailure, scope: AjaxObject }; // Start the transaction. AjaxObject.startRequest();
/* * AjaxObject is a hypothetical object that encapsulates the transaction * request and callback logic. * * handleSuccess( ) provides success case logic * handleFailure( ) provides failure case logic * processResult( ) displays the results of the response from both the * success and failure handlers * call( ) calling this member starts the transaction request. */ var AjaxObject = { handleSuccess:function(o) { // This member handles the success response // and passes the response object o to AjaxObject's // processResult member. this.processResult(o); }, handleFailure:function(o) { // Failure handler }, processResult:function(o) { // This member is called by handleSuccess }, startRequest:function() { YAHOO.util.Connect.asyncRequest('POST', 'php/post.php', callback, "new=1&old=2"); } }; /* * Define the callback object for success and failure * handlers as well as object scope. */ var callback = { success:AjaxObject.handleSuccess, failure:AjaxObject.handleFailure, scope: AjaxObject }; // Start the transaction. AjaxObject.startRequest();
Each transaction can be defined with a time threshold and if the transaction has not completed by that
threshold, it will automatically call abort
. If successful, the failure
handler will
be called. Please see section Failure Case for more details on the response object signature in an abort
scenario.
/* * In this example, the callback object has a new property: * timeout. This property is defined with a value, * in milliseconds, of 5000 as the abort threshold. If * the transaction has not completed by 5000ms, the * transaction will abort. */ var callback = { success: function(o) {/*success handler code*/}, failure: function(o) {/*failure handler code*/}, timeout: 5000, argument: [argument1, argument2, argument3] };
/* * In this example, the callback object has a new property: * timeout. This property is defined with a value, * in milliseconds, of 5000 as the abort threshold. If * the transaction has not completed by 5000ms, the * transaction will abort. */ var callback = { success: function(o) {/*success handler code*/}, failure: function(o) {/*failure handler code*/}, timeout: 5000, argument: [argument1, argument2, argument3] };
In a success case, a response object with the following properties is passed to the callback object's success handler:
property | description |
---|---|
tId | The unique, incremented id for the transaction. |
status | The HTTP status code of the resulting transaction. |
statusText | The message associated with the HTTP status. |
getResponseHeader[label] | Returns the string value of the specified header label. |
getAllResponseHeaders | All returned HTTP headers available as a string. Each label-value pair is delimited by "\n". |
responseText | The server's response as a string. |
responseXML | The server's response as a XML document. |
argument | The user-defined argument or arguments as defined in the callback object. |
If the server responds with an error or fails to respond at all, Connection
Manager tries to capture as much information as possible about the transaction
and pass an object to the callback object's failure
handler.
The properties of this response object are the same as in a success case — Connection
Manager populates all properties for which it can derive adequate information
from the server's response.
If the server cannot or does not respond to the HTTP request, however, there may not be a readable response. If a transaction is terminated by the server in such a way that no readable response is available, the callback object's failure handler receives an object with the following properties:
property | description |
---|---|
tId | The transaction id |
status | 0 |
statusText | "communication failure" |
argument | The user-defined argument or arguments as defined as the callback object. |
If an abort
occurred and the transaction was successfully cancelled, the callback object's
failure handler receives an object with the following properties:
property | description |
---|---|
tId | The transaction id |
status | -1 |
statusText | "transaction aborted" |
argument | The user-defined argument or arguments as defined as the callback object. |
Since file uploading occurs through an iframe, traditional response data such as HTTP status codes are not directly available, and connection manager cannot reasonably discern success or failure (except a transaction timeout). Instead, the callback's upload handler will receive a response object containing the body of the iframe document, as a string, when the transaction is complete. Rather than enforce a document pattern, you can customize the upload response to contain the necessary markup and, or script. In the event a transaction timeout is defined, and the timeout threshold is reached, the failure handler will be used.
property | description |
---|---|
tId | The transaction id |
responseText | The markup, within the iframe document's body tag, as a string, if available |
responseXML | The response data as an XML document, if available. |
argument | The user-defined argument or arguments as defined as the callback object. |
Connection Manager can automatically harvest HTML form data and prepare
it for either a GET or POST request via the setForm
method.
When you call this method before initiating the transaction, Connection Manager
constructs a GET querystring or a POST message from the form
and submits it to the specified URL. To use this functionality, your form
elements must have defined, non-empty string name attribute values.
setForm
will encode each HTML form field's name and value using encodeURIComponent
.
This results in a string of UTF-8 encoded, name-value pairs. NOTE: Setting an HTTP header of "Content-Type" with
a different charset value will not change the encoding of the serialized data.
If the subsequent asyncRequest
is HTTP GET and has a URI querystring, the querystring resulting
from setForm
will be concatenated onto the URI's existing querystring.
If the transaction is HTTP POST, and asyncRequest
contains additional POST data -- as the fourth
argument -- this data will be added to the form data to create the POST message.
// argument formId can be the id or name attribute value of the // HTML form, or an HTML form object. var formObject = document.getElementById('aForm'); YAHOO.util.Connect.setForm(formObject); // This example facilitates a POST transaction. The POST data(HTML form) // are initialized when calling setForm(), and it is automatically // included when calling asyncRequest. var cObj = YAHOO.util.Connect.asyncRequest('POST', 'http://www.yahoo.com', callback);
// argument formId can be the id or name attribute value of the // HTML form, or an HTML form object. var formObject = document.getElementById('aForm'); YAHOO.util.Connect.setForm(formObject); // This example facilitates a POST transaction. The POST data(HTML form) // are initialized when calling setForm(), and it is automatically // included when calling asyncRequest. var cObj = YAHOO.util.Connect.asyncRequest('POST', 'http://www.yahoo.com', callback);
setForm
can also upload files, if form elements of input type="file" are present, as
part of a form submission. To enable file uploading, set the second argument of setForm
to true.
When the transaction is complete, the callback object's upload method will be called.
// argument formId can be the id or name attribute value of the // HTML form, or an HTML form object. var formObject = document.getElementById('aForm'); // the second argument is true to indicate file upload. YAHOO.util.Connect.setForm(formObject, true); var cObj = YAHOO.util.Connect.asyncRequest('POST', 'http://www.yahoo.com', callback);
// argument formId can be the id or name attribute value of the // HTML form, or an HTML form object. var formObject = document.getElementById('aForm'); // the second argument is true to indicate file upload. YAHOO.util.Connect.setForm(formObject, true); var cObj = YAHOO.util.Connect.asyncRequest('POST', 'http://www.yahoo.com', callback);
When uploading files in applications over SSL and using IE, set the third argument to true to prevent IE from throwing domain security errors.
// the third argument is set true to have Connection Manager // set the iframe source to "javascript:false". YAHOO.util.Connect.setForm(formObject, true, true);
// the third argument is set true to have Connection Manager // set the iframe source to "javascript:false". YAHOO.util.Connect.setForm(formObject, true, true);
Connection Manager can be configured to use Flash to make cross-domain(XDR), HTTP transactions. The transport
dependency "connection.swf" must be avaiable and initialized prior to making any XDR transactions. For each XDR
transaction, the callback object's xdr
property must be defined as true
. This will
instruct Connection Manager to use the alternate transport instead of using XMLHttpRequest.
The dependency connection.swf is written in ActionScript 3, so Flash Player 9 or better is required (version 9.0.124 or better is recommended). Additionally, a cross-domain policy file must be deployed at the resource to grant the client access to the remote domain. A cross-domain request will not be successful without this policy file hosted at the resource. The following example file grants permissive access to the resource from all requests originating from yahoo.com:
<?xml version="1.0"?> <!DOCTYPE cross-domain-policy SYSTEM "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd"> <cross-domain-policy> <allow-access-from domain="*.yahoo.com"/> </cross-domain-policy>
<?xml version="1.0"?> <!DOCTYPE cross-domain-policy SYSTEM "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd"> <cross-domain-policy> <allow-access-from domain="*.yahoo.com"/> </cross-domain-policy>
XDR transactions, using the Flash transport, provide a subset of the full response data in XMLHttpRequest object. Specifically, it does not reveal data such as HTTP headers and status, and only the responseText property is supported.
property | description |
---|---|
tId | The transaction id |
responseText | The server's response as a string. |
argument | The user-defined argument or arguments as defined as the callback object. |
The following examples demonstrates a cross-domain transaction retrieving data from the Yahoo! Weather RSS feed at http://xml.weather.yahoo.com/:
var YCM = YAHOO.util.Connect, // The resource is Yahoo! Pipes, returning JSON data. uri = "http://pipes.yahooapis.com/pipes/pipe.run?_id=giWz8Vc33BG6rQEQo_NLYQ&_render=json", request, callback, responseSuccess, responseFailure; responseSuccess = function(o){ * The argument 'o' is the response object. Its * properties are: * * - tId * - responseText * - argument }; responseFailure = function(o){ // See the comments for responseSuccess. }; // Create a callback object that defines success and failure // handlers, and instructs Connection Manager to use the // Flash transport by defining the xdr property and setting // it to true. callback = { success:responseSuccess, failure:responseFailure, xdr: true, // Use the Flash transport instead of XMLHttpRequest argument:['foo', 'bar'] }; function makeRequest() { // Send request to xml.weather.yahoo.com request = YCM.asyncRequest('GET', uri, callback); } // Initialize the Flash transport for XDR YCM.transport('connection.swf'); // Subscribe to xdrReadyEvent, which is fired // when connection.swf's finishes loading, and // call function request(). YCM.xdrReadyEvent.subscribe(makeRequest);
var YCM = YAHOO.util.Connect, // The resource is Yahoo! Pipes, returning JSON data. uri = "http://pipes.yahooapis.com/pipes/pipe.run?_id=giWz8Vc33BG6rQEQo_NLYQ&_render=json", request, callback, responseSuccess, responseFailure; responseSuccess = function(o){ * The argument 'o' is the response object. Its * properties are: * * - tId * - responseText * - argument }; responseFailure = function(o){ // See the comments for responseSuccess. }; // Create a callback object that defines success and failure // handlers, and instructs Connection Manager to use the // Flash transport by defining the xdr property and setting // it to true. callback = { success:responseSuccess, failure:responseFailure, xdr: true, // Use the Flash transport instead of XMLHttpRequest argument:['foo', 'bar'] }; function makeRequest() { // Send request to xml.weather.yahoo.com request = YCM.asyncRequest('GET', uri, callback); } // Initialize the Flash transport for XDR YCM.transport('connection.swf'); // Subscribe to xdrReadyEvent, which is fired // when connection.swf's finishes loading, and // call function request(). YCM.xdrReadyEvent.subscribe(makeRequest);
Connection Manager implements YAHOO.util.CustomEvent
to provide a variety of custom events during
the course of a transaction. The following table describes the list of Connection Manager's custom events:
Custom Event | Description |
---|---|
startEvent | This event fires at the start of a transaction and passes the transaction's ID to its subscribed handler. |
completeEvent | This event fires when a transaction response has completed and passes the transaction's ID to its subscribed handler. |
successEvent | This event fires when a transaction response is complete and determined to be HTTP 2xx. The response object is passed to successEvent's subscribed handler. This event is analogous to the callback success handler. NOTE: This event does not fire for file upload transactions. |
failureEvent | This event fires when a transaction response is complete and determined to be HTTP 4xx/5xx or if an HTTP status is unavailable. The response object is passed to failureEvent's subscribed handler. This event is analogous to the callback failure handler. |
uploadEvent | This event fires when a file upload transaction is complete. This event fires only for file upload transaction, in place of successEvent and failureEvent. The response object is passed to the uploadEvent's subscribed handler. This event is analogous to the callback upload handler. |
abortEvent | This event fires when a transaction's callback.timeout triggers an abort or
explicitly via YAHOO.util.Connect.abort(). |
Connection Manager custom events are fired at the global level and can also fire at the transaction level. One common use case for subscribing to global events is where a set of common event handlers are created to respond to all possible custom events. In such a scenario, subscribing to global events is quite simple. The following example demonstrate how to subscribe to global custom events:
// Create a shorthand for YAHOO.util.Connect var YUC = YAHOO.util.Connect; /* * Create an object to handle all of the Connection Manager custom events. * * NOTE: You can also choose to represent your event handlers as global * functions instead of object members, and omit the scope argument from * subscribe(). */ var handleEvents = { start: function(eventType, args) { // do something when startEvent fires. // Argument eventType will have a string value of: startEvent // Argument args is an array, and the response object will be the // first element in the array. The response object will have one // property: tId (the transaction ID). }, complete: function(eventType, args) { // do something when completeEvent fires. }, success: function(eventType, args) { // do something when successEvent fires. }, failure: function(eventType, args) { // do something when failureEvent fires. }, // Define this event handler for file upload transactions *only*. // This handler will not be used for any other transaction cases. upload: function(eventType, args) { // do something when uploadEvent fires. }, abort: function(eventType, args) { // do something when abortEvent fires. } }; /* * This example shows how to subscribe to all custom events fired at the * Connection Manager level. When subscribed, the custom event will fire * for all transactions. */ // Subscribe to all custom events fired by Connection Manager. // Pass in the *globalEvents* object as the second argument to provide // the necessary scope correction for any usage of the *this* keyword // in any of the handler functions. YUC.startEvent.subscribe(handleEvents.start, handleEvents); YUC.completeEvent.subscribe(handleEvents.complete, handleEvents); // This event will not fire for file upload transactions. Instead, // subscribe to the uploadEvent. YUC.successEvent.subscribe(handleEvents.success, handleEvents); // This event will not fire for file upload transactions. Instead, // subscribe to the uploadEvent. YUC.failureEvent.subscribe(handleEvents.failure, handleEvents); // This event is fired only for file upload transactions in place of // successEvent and failureEvent YUC.uploadEvent.subscribe(handleEvents.upload, handleEvents); YUC.abortEvent.subscribe(handleEvents.abort, handleEvents); /* * NOTE: You do not need to pass a callback object to asyncRequest() * since your handlers are already subscribed at the Connection * Manager level. The callback object omits any success or failure * logic since those cases are already available and subscribed to as * custom events. You can still include callback.success and * callback.failure, and they will be processed; but, it will also be * a redundant action. */ var transaction = YUC.asyncRequest('GET', sUrl, { timeout: 3000 });
// Create a shorthand for YAHOO.util.Connect var YUC = YAHOO.util.Connect; /* * Create an object to handle all of the Connection Manager custom events. * * NOTE: You can also choose to represent your event handlers as global * functions instead of object members, and omit the scope argument from * subscribe(). */ var handleEvents = { start: function(eventType, args) { // do something when startEvent fires. // Argument eventType will have a string value of: startEvent // Argument args is an array, and the response object will be the // first element in the array. The response object will have one // property: tId (the transaction ID). }, complete: function(eventType, args) { // do something when completeEvent fires. }, success: function(eventType, args) { // do something when successEvent fires. }, failure: function(eventType, args) { // do something when failureEvent fires. }, // Define this event handler for file upload transactions *only*. // This handler will not be used for any other transaction cases. upload: function(eventType, args) { // do something when uploadEvent fires. }, abort: function(eventType, args) { // do something when abortEvent fires. } }; /* * This example shows how to subscribe to all custom events fired at the * Connection Manager level. When subscribed, the custom event will fire * for all transactions. */ // Subscribe to all custom events fired by Connection Manager. // Pass in the *globalEvents* object as the second argument to provide // the necessary scope correction for any usage of the *this* keyword // in any of the handler functions. YUC.startEvent.subscribe(handleEvents.start, handleEvents); YUC.completeEvent.subscribe(handleEvents.complete, handleEvents); // This event will not fire for file upload transactions. Instead, // subscribe to the uploadEvent. YUC.successEvent.subscribe(handleEvents.success, handleEvents); // This event will not fire for file upload transactions. Instead, // subscribe to the uploadEvent. YUC.failureEvent.subscribe(handleEvents.failure, handleEvents); // This event is fired only for file upload transactions in place of // successEvent and failureEvent YUC.uploadEvent.subscribe(handleEvents.upload, handleEvents); YUC.abortEvent.subscribe(handleEvents.abort, handleEvents); /* * NOTE: You do not need to pass a callback object to asyncRequest() * since your handlers are already subscribed at the Connection * Manager level. The callback object omits any success or failure * logic since those cases are already available and subscribed to as * custom events. You can still include callback.success and * callback.failure, and they will be processed; but, it will also be * a redundant action. */ var transaction = YUC.asyncRequest('GET', sUrl, { timeout: 3000 });
In additional to global custom events, the same events can be fired for specific transactions by defining custom
event handlers in the callback object. To subscribe to these custom events, create the
member *customevents* in the callback object and create handlers for as many custom events as desired. The
following code example shows how to define callback.customevents
and the callback signatures:
var callback = { customevents:{ onStart: function(eventType, args) { // eventType has a string value of "startEvent". // args[0].tId is the integer transaction ID. // args[1] contains the value of <code>callback.argument</code>, if callback.argument is defined. }, onComplete: function(eventType, args) { // eventType has a string value of "completeEvent". // args[0].tId is the integer transaction ID. // args[1] contains the value of <code>callback.argument</code>, if callback.argument is defined. }, onSuccess: function(eventType, args) { /* * eventType has a string value of "successEvent". * args[0] is the response object, which has the * following properties: * * args[0].tId * args[0].status * args[0].statusText * args[0].getResponseHeader[ ] * args[0].getAllResponseHeaders * args[0].responseText * args[0].responseXML * args[0].argument */ }, onFailure: function(eventType, args) { // eventType has a string value of "failureEvent". // args[0] is the response object. }, // Define this event handler for file upload transactions *only*. // This handler will not be used for any other transaction cases. onUpload: function(eventType, args) { // eventType has a string value of "uploadEvent". // args[0] is the response object. }, onAbort: function(eventType, args) { // eventType has a string value of "abortEvent". // args[0].tId is the integer transaction ID. // args[1] contains the value of <code>callback.argument</code>, if callback.argument is defined. } } };
var callback = { customevents:{ onStart: function(eventType, args) { // eventType has a string value of "startEvent". // args[0].tId is the integer transaction ID. // args[1] contains the value of <code>callback.argument</code>, if callback.argument is defined. }, onComplete: function(eventType, args) { // eventType has a string value of "completeEvent". // args[0].tId is the integer transaction ID. // args[1] contains the value of <code>callback.argument</code>, if callback.argument is defined. }, onSuccess: function(eventType, args) { /* * eventType has a string value of "successEvent". * args[0] is the response object, which has the * following properties: * * args[0].tId * args[0].status * args[0].statusText * args[0].getResponseHeader[ ] * args[0].getAllResponseHeaders * args[0].responseText * args[0].responseXML * args[0].argument */ }, onFailure: function(eventType, args) { // eventType has a string value of "failureEvent". // args[0] is the response object. }, // Define this event handler for file upload transactions *only*. // This handler will not be used for any other transaction cases. onUpload: function(eventType, args) { // eventType has a string value of "uploadEvent". // args[0] is the response object. }, onAbort: function(eventType, args) { // eventType has a string value of "abortEvent". // args[0].tId is the integer transaction ID. // args[1] contains the value of <code>callback.argument</code>, if callback.argument is defined. } } };
The following example demonstrates the creation of a specific object to handle custom events, and the creation of the callback object used in the transaction:
/* * Create an event handler object to handle a transaction's custom events. * * NOTE: You can also choose to represent your event handlers as global * functions instead of object members, and omit the scope argument from * the callback. * * This example demonstrates a non-file upload transaction, hence the * handler onUpload is not defined. */ var handleEvent = { start: function(eventType, args) { // do something when startEvent fires. }, complete: function(eventType, args) { // do something when completeEvent fires. }, success: function(eventType, args) { // do something when successEvent fires. }, failure: function(eventType, args) { // do something when failureEvent fires. }, abort: function(eventType, args) { // do something when abortEvent fires. } }; /* * This example shows how to subscribe to all custom events. * Pass the *handleEvent* object as the second argument to provide * the necessary scope correction for any usage of the *this* keyword * in any of the handler functions. * * NOTE: All events are subscribed in this example, but you can choose * to subscribe to any combination of custom events desired. None are * mandatory. */ // Define the scope property with a value of *handleEvent* to provide // the necessary scope correction for any usage of the *this* keyword // in any of the handler functions. /* Callback object with custom events defined */ var callback = { customevents: { onStart: handleEvent.start, onComplete: handleEvent.complete, onSuccess: handleEvent.success, onFailure: handleEvent.failure, onAbort: handleEvent.abort }, scope:handleEvent, argument: ["foo", "bar", "baz"] }; var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);
/* * Create an event handler object to handle a transaction's custom events. * * NOTE: You can also choose to represent your event handlers as global * functions instead of object members, and omit the scope argument from * the callback. * * This example demonstrates a non-file upload transaction, hence the * handler onUpload is not defined. */ var handleEvent = { start: function(eventType, args) { // do something when startEvent fires. }, complete: function(eventType, args) { // do something when completeEvent fires. }, success: function(eventType, args) { // do something when successEvent fires. }, failure: function(eventType, args) { // do something when failureEvent fires. }, abort: function(eventType, args) { // do something when abortEvent fires. } }; /* * This example shows how to subscribe to all custom events. * Pass the *handleEvent* object as the second argument to provide * the necessary scope correction for any usage of the *this* keyword * in any of the handler functions. * * NOTE: All events are subscribed in this example, but you can choose * to subscribe to any combination of custom events desired. None are * mandatory. */ // Define the scope property with a value of *handleEvent* to provide // the necessary scope correction for any usage of the *this* keyword // in any of the handler functions. /* Callback object with custom events defined */ var callback = { customevents: { onStart: handleEvent.start, onComplete: handleEvent.complete, onSuccess: handleEvent.success, onFailure: handleEvent.failure, onAbort: handleEvent.abort }, scope:handleEvent, argument: ["foo", "bar", "baz"] }; var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);
When using Connection Manager, there are some ways to ensure the transaction originated from your application instead of a forged request. One practice involves the use of user-specific signatures in the transaction. Your application server can generate a pre-computed signature for use when the client initiates a request. The following example demonstrate the creation of signatures using PHP and MD5 hashing, and using YUI Connection Manager to initiate a transaction containing the signature.
// $deleteRecordToken can be any additional, random sequence concatenated onto $username. // to salt the string which is converted to an MD5 hash. $transaction_signature = md5($username . $deleteRecordToken);
// $deleteRecordToken can be any additional, random sequence concatenated onto $username. // to salt the string which is converted to an MD5 hash. $transaction_signature = md5($username . $deleteRecordToken);
/* * Create a custom header -- in this case "X-Signature" -- using * connection manager with the signature as its value, and initiate * the transaction. The transaction is sent to "/delete_record.php". */ YAHOO.util.Connect.initHeader('X-Signature', '<? echo $transaction_signature ?>'); var request = YAHOO.util.Connect.asyncRequest('GET', '/delete_record.php', callback);
/* * Create a custom header -- in this case "X-Signature" -- using * connection manager with the signature as its value, and initiate * the transaction. The transaction is sent to "/delete_record.php". */ YAHOO.util.Connect.initHeader('X-Signature', '<? echo $transaction_signature ?>'); var request = YAHOO.util.Connect.asyncRequest('GET', '/delete_record.php', callback);
Upon receiving the request from the client, determine its authenticity by verifying the signature before taking action. Perform the same hashing operation and compare it to the signature received. If the signatures do not match, do not proceed with the intended operation.
$transaction_signature = md5($username . $deleteRecordToken); if ($_SERVER['HTTP_X_SIGNATURE'] === $transaction_signature) { // proceed with delete operation // ... } else { // there is a problem // ... }
$transaction_signature = md5($username . $deleteRecordToken); if ($_SERVER['HTTP_X_SIGNATURE'] === $transaction_signature) { // proceed with delete operation // ... } else { // there is a problem // ... }
Signatures can also be use with GET requests, sent as a query string or part of a query string.
$transaction_signature = md5($username . $deleteRecordToken); // $uri is the resource and the querystring includes the // signature. $uri = '/delete_record.php?signature=' . $transaction_signature;
$transaction_signature = md5($username . $deleteRecordToken); // $uri is the resource and the querystring includes the // signature. $uri = '/delete_record.php?signature=' . $transaction_signature;
var request = YAHOO.util.Connect.asyncRequest('GET', '<? echo $uri ?>', callback);
var request = YAHOO.util.Connect.asyncRequest('GET', '<? echo $uri ?>', callback);
With POST requests, the signature is sent as part of the data.
$transaction_signature = md5($username . $updateRecordToken);
$transaction_signature = md5($username . $updateRecordToken);
// postData represents the data sent in the POST request, // and the signature is sent as part of the POST message. var request = YAHOO.util.Connect.asyncRequest('POST', '/update_record.php', callback, postData + '&signature=<? echo $transaction_signature ?>');
// postData represents the data sent in the POST request, // and the signature is sent as part of the POST message. var request = YAHOO.util.Connect.asyncRequest('POST', '/update_record.php', callback, postData + '&signature=<? echo $transaction_signature ?>');
The method isCallInProgress
can be used to determine if an asynchronous transaction
has not yet completed. The method will return true
if the transaction is still in progress.
//Initiate an asynchronous transaction. var cObj = YAHOO.util.Connect.asyncRequest('GET','http://www.yahoo.com',callback); //isCallInProgress will return true if the transaction has not been completed. var callStatus = YAHOO.util.Connect.isCallInProgress(cObj);
//Initiate an asynchronous transaction. var cObj = YAHOO.util.Connect.asyncRequest('GET','http://www.yahoo.com',callback); //isCallInProgress will return true if the transaction has not been completed. var callStatus = YAHOO.util.Connect.isCallInProgress(cObj);
To explicitly cancel a transaction in progress, call the abort
method and pass the connection
object — returned by asyncRequest
— as an argument. abort
will return
true if the transaction was successfully aborted or false if the transaction has completed before the abort call.
//Initiate an asynchronous transaction. var cObj = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback); //Abort the transaction if it isn't completed in ten seconds. setTimeout(function() { YAHOO.util.Connect.abort(cObj) },10000);
//Initiate an asynchronous transaction. var cObj = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback); //Abort the transaction if it isn't completed in ten seconds. setTimeout(function() { YAHOO.util.Connect.abort(cObj) },10000);
To use the transaction's callback failure handler upon abort
, add the callback object as the
second argument.
/* * Abort the transaction if it isn't completed in ten seconds, * and pass the callback with a defined failure handler as the * second argument. The failure callback will receive a response * object with properties as described in the abort subsection of * Failure Case. * * abort() will return true if the transaction was successfully * aborted. Otherwise, it will return false. * */ setTimeout(function() { YAHOO.util.Connect.abort(cObj, callback) },10000);
/* * Abort the transaction if it isn't completed in ten seconds, * and pass the callback with a defined failure handler as the * second argument. The failure callback will receive a response * object with properties as described in the abort subsection of * Failure Case. * * abort() will return true if the transaction was successfully * aborted. Otherwise, it will return false. * */ setTimeout(function() { YAHOO.util.Connect.abort(cObj, callback) },10000);
When using Firefox 3.0, all HTTP POST transactions automatically receive a Content-Type
header of
application/x-www-form-urlencoded; charset=UTF-8
, effectively enforcing UTF-8 encoding for all POST
transactions.
The YUI Library and related topics are discussed on the on the YUILibrary.com forums.
Also be sure to check out YUIBlog for updates and articles about the YUI Library written by the library's developers.
The YUI Library's public bug tracking and feature request repositories are located on the YUILibrary.com site. Before filing new feature requests or bug reports, please review our reporting guidelines.
All YUI 2.x users should review the YUI 2.8.2 security bulletin, which discusses a vulnerability present in YUI 2.4.0-2.8.1.
Copyright © 2013 Yahoo! Inc. All rights reserved.