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.

YUI 2: Connection Manager

YUI 2: Connection Manager

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.

Getting Started

To use Connection Manager, include the source file and its dependency in your web page with the script tag:

  1. <!-- Dependency -->
  2. <script src="http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js"></script>
  3.  
  4. <!-- Used for Custom Events and event listener bindings -->
  5. <script src="http://yui.yahooapis.com/2.9.0/build/event/event-min.js"></script>
  6.  
  7. <!-- Source file -->
  8. <!--
  9. If you require only basic HTTP transaction support, use the
  10. connection_core.js file.
  11. -->
  12. <script src="http://yui.yahooapis.com/2.9.0/build/connection/connection_core-min.js"></script>
  13.  
  14. <!--
  15. Use the full connection.js if you require the following features:
  16. - Form serialization.
  17. - File Upload using the iframe transport.
  18. - Cross-domain(XDR) transactions.
  19. -->
  20. <script src="http://yui.yahooapis.com/2.9.0/build/connection/connection-min.js"></script>
  21.  
<!-- 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>
 

YUI dependency configurator.

YUI Dependency Configurator:

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.

  1. var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback, null);
  2.  
var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback, null);
 

In this code:

  • The YAHOO.util.Connect.asyncRequest method initiates an asynchronous transaction (using XMLHttpRequest) and returns a reference to that transaction.
  • The first argument of asyncRequest specifies the HTTP method; this transaction uses HTTP GET. Other possible methods include: POST, HEAD, PUT, DELETE(HEAD, PUT and DELETE may not be supported by all A-Grade browsers ).
  • The second argument — variable sUrl — is a qualified URL.
  • The third argument — variable callback — is a reference to a defined callback object(or an object written inline), which handles the server response.
  • The fourth argument accommodates a POST message for POST transactions. Because this example illustrates a GET transaction, the POST message argument can be ignored or set to null.

Using Connection Manager

This section describes several common uses of the Connection Manager. It contains these subsections:

Asynchronous Transactions and the Callback Object

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:

  • success: a function called when the server responds with a valid HTTP response.
  • failure: a function called when the server response indicates that a problem, such as an HTTP 404 (file not found) error, has occurred.
  • argument: an object, string, number, or array containing data that your success and failure functions might need in order to successfully process the server response.

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.

  1. /*
  2.  * This is an example callback object with success
  3.  * and failure members defined inline. The argument
  4.  * property demonstrates how to pass multiple values
  5.  * to the callback as an array.
  6.  */
  7. var callback = {
  8. success: function(o) {/*success handler code*/},
  9. failure: function(o) {/*failure handler code*/},
  10. argument: [argument1, argument2, argument3]
  11. };
  12.  
/*
 * 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.

  1. // Passing an example of array of arguments to both
  2. // the success and failure callback handlers.
  3. var args = ['foo','bar'];
  4.  
  5. var responseSuccess = function(o) {
  6. /* Please see the Success Case section for more
  7.  * details on the response object's properties.
  8.  * o.tId
  9.  * o.status
  10.  * o.statusText
  11.  * o.getResponseHeader[ ]
  12.  * o.getAllResponseHeaders
  13.  * o.responseText
  14.  * o.responseXML
  15.  * o.argument
  16.  */
  17. };
  18.  
  19. var responseFailure = function(o) {
  20. // Access the response object's properties in the
  21. // same manner as listed in responseSuccess( ).
  22. // Please see the Failure Case section and
  23. // Communication Error sub-section for more details on the
  24. // response object's properties.
  25. };
  26.  
  27. var callback = {
  28. success:responseSuccess,
  29. failure:responseFailure,
  30. argument:args
  31. };
  32.  
// 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
};
 

Override Caching

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.

  1. /*
  2.  * Set callback.cache to false to override HTTP GET caching.
  3.  * A key-value of rnd=timestamp will be added to the
  4.  * querystring.
  5.  */
  6. var callback = {
  7. cache:false
  8. };
  9.  
/*
 * 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
};
 

The Callback Object and File Upload

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.

  1. /*
  2.  * This is an example callback object with upload
  3.  * and argument members defined inline. The argument
  4.  * property demonstrates how to pass multiple values
  5.  * to the upload handler as an array.
  6.  */
  7. var callback = {
  8. upload: function(o) {/*upload handler code*/},
  9. argument: [argument1, argument2, argument3]
  10. };
  11.  
/*
 * 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]
};
 

The Callback Object and Scope

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.

  1. /*
  2.  * AjaxObject is a hypothetical object that encapsulates the transaction
  3.  * request and callback logic.
  4.  *
  5.  * handleSuccess( ) provides success case logic
  6.  * handleFailure( ) provides failure case logic
  7.  * processResult( ) displays the results of the response from both the
  8.  * success and failure handlers
  9.  * call( ) calling this member starts the transaction request.
  10.  */
  11.  
  12. var AjaxObject = {
  13.  
  14. handleSuccess:function(o) {
  15. // This member handles the success response
  16. // and passes the response object o to AjaxObject's
  17. // processResult member.
  18. this.processResult(o);
  19. },
  20.  
  21. handleFailure:function(o) {
  22. // Failure handler
  23. },
  24.  
  25. processResult:function(o) {
  26. // This member is called by handleSuccess
  27. },
  28.  
  29. startRequest:function() {
  30. YAHOO.util.Connect.asyncRequest('POST', 'php/post.php', callback, "new=1&old=2");
  31. }
  32.  
  33. };
  34.  
  35. /*
  36.  * Define the callback object for success and failure
  37.  * handlers as well as object scope.
  38.  */
  39. var callback = {
  40. success:AjaxObject.handleSuccess,
  41. failure:AjaxObject.handleFailure,
  42. scope: AjaxObject
  43. };
  44.  
  45. // Start the transaction.
  46. AjaxObject.startRequest();
  47.  
/*
 * 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();
 

The Callback Object and Timeout

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.

  1. /*
  2. * In this example, the callback object has a new property:
  3. * timeout. This property is defined with a value,
  4. * in milliseconds, of 5000 as the abort threshold. If
  5. * the transaction has not completed by 5000ms, the
  6. * transaction will abort.
  7. */
  8. var callback = {
  9. success: function(o) {/*success handler code*/},
  10. failure: function(o) {/*failure handler code*/},
  11. timeout: 5000,
  12. argument: [argument1, argument2, argument3]
  13. };
  14.  
	/*
	 * 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]
	};
 

Success Case

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.

Failure Case

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.

Upload Case

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.

Forms and File Upload

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.

  1. // argument formId can be the id or name attribute value of the
  2. // HTML form, or an HTML form object.
  3. var formObject = document.getElementById('aForm');
  4. YAHOO.util.Connect.setForm(formObject);
  5. // This example facilitates a POST transaction. The POST data(HTML form)
  6. // are initialized when calling setForm(), and it is automatically
  7. // included when calling asyncRequest.
  8. var cObj = YAHOO.util.Connect.asyncRequest('POST', 'http://www.yahoo.com', callback);
  9.  
// 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.

  1. // argument formId can be the id or name attribute value of the
  2. // HTML form, or an HTML form object.
  3. var formObject = document.getElementById('aForm');
  4.  
  5. // the second argument is true to indicate file upload.
  6. YAHOO.util.Connect.setForm(formObject, true);
  7.  
  8. var cObj = YAHOO.util.Connect.asyncRequest('POST', 'http://www.yahoo.com', callback);
  9.  
   // 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.

  1. // the third argument is set true to have Connection Manager
  2. // set the iframe source to "javascript:false".
  3. YAHOO.util.Connect.setForm(formObject, true, true);
  4.  
// the third argument is set true to have Connection Manager
// set the iframe source to "javascript:false".
YAHOO.util.Connect.setForm(formObject, true, true);
 

Cross-Domain Requests

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:

  1. <?xml version="1.0"?>
  2. <!DOCTYPE cross-domain-policy SYSTEM
  3. "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">
  4. <cross-domain-policy>
  5. <allow-access-from domain="*.yahoo.com"/>
  6. </cross-domain-policy>
  7.  
<?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/:

  1. var YCM = YAHOO.util.Connect,
  2. // The resource is Yahoo! Pipes, returning JSON data.
  3. uri = "http://pipes.yahooapis.com/pipes/pipe.run?_id=giWz8Vc33BG6rQEQo_NLYQ&_render=json",
  4. request, callback, responseSuccess, responseFailure;
  5.  
  6. responseSuccess = function(o){
  7. * The argument 'o' is the response object. Its
  8. * properties are:
  9. *
  10. * - tId
  11. * - responseText
  12. * - argument
  13. };
  14.  
  15. responseFailure = function(o){
  16. // See the comments for responseSuccess.
  17. };
  18.  
  19. // Create a callback object that defines success and failure
  20. // handlers, and instructs Connection Manager to use the
  21. // Flash transport by defining the xdr property and setting
  22. // it to true.
  23. callback = {
  24. success:responseSuccess,
  25. failure:responseFailure,
  26. xdr: true, // Use the Flash transport instead of XMLHttpRequest
  27. argument:['foo', 'bar']
  28. };
  29.  
  30. function makeRequest() {
  31. // Send request to xml.weather.yahoo.com
  32. request = YCM.asyncRequest('GET', uri, callback);
  33. }
  34.  
  35. // Initialize the Flash transport for XDR
  36. YCM.transport('connection.swf');
  37.  
  38. // Subscribe to xdrReadyEvent, which is fired
  39. // when connection.swf's finishes loading, and
  40. // call function request().
  41. YCM.xdrReadyEvent.subscribe(makeRequest);
  42.  
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);
 

Transactions and Custom Events

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:

  1. // Create a shorthand for YAHOO.util.Connect
  2. var YUC = YAHOO.util.Connect;
  3.  
  4. /*
  5.  * Create an object to handle all of the Connection Manager custom events.
  6.  *
  7.  * NOTE: You can also choose to represent your event handlers as global
  8.  * functions instead of object members, and omit the scope argument from
  9.  * subscribe().
  10.  */
  11. var handleEvents = {
  12. start: function(eventType, args) {
  13. // do something when startEvent fires.
  14. // Argument eventType will have a string value of: startEvent
  15. // Argument args is an array, and the response object will be the
  16. // first element in the array. The response object will have one
  17. // property: tId (the transaction ID).
  18. },
  19.  
  20. complete: function(eventType, args) {
  21. // do something when completeEvent fires.
  22. },
  23.  
  24. success: function(eventType, args) {
  25. // do something when successEvent fires.
  26. },
  27.  
  28. failure: function(eventType, args) {
  29. // do something when failureEvent fires.
  30. },
  31.  
  32. // Define this event handler for file upload transactions *only*.
  33. // This handler will not be used for any other transaction cases.
  34. upload: function(eventType, args) {
  35. // do something when uploadEvent fires.
  36. },
  37.  
  38. abort: function(eventType, args) {
  39. // do something when abortEvent fires.
  40. }
  41. };
  42.  
  43. /*
  44.  * This example shows how to subscribe to all custom events fired at the
  45.  * Connection Manager level. When subscribed, the custom event will fire
  46.  * for all transactions.
  47.  */
  48.  
  49. // Subscribe to all custom events fired by Connection Manager.
  50. // Pass in the *globalEvents* object as the second argument to provide
  51. // the necessary scope correction for any usage of the *this* keyword
  52. // in any of the handler functions.
  53. YUC.startEvent.subscribe(handleEvents.start, handleEvents);
  54. YUC.completeEvent.subscribe(handleEvents.complete, handleEvents);
  55.  
  56. // This event will not fire for file upload transactions. Instead,
  57. // subscribe to the uploadEvent.
  58. YUC.successEvent.subscribe(handleEvents.success, handleEvents);
  59.  
  60. // This event will not fire for file upload transactions. Instead,
  61. // subscribe to the uploadEvent.
  62. YUC.failureEvent.subscribe(handleEvents.failure, handleEvents);
  63.  
  64. // This event is fired only for file upload transactions in place of
  65. // successEvent and failureEvent
  66. YUC.uploadEvent.subscribe(handleEvents.upload, handleEvents);
  67. YUC.abortEvent.subscribe(handleEvents.abort, handleEvents);
  68.  
  69. /*
  70.  * NOTE: You do not need to pass a callback object to asyncRequest()
  71.  * since your handlers are already subscribed at the Connection
  72.  * Manager level. The callback object omits any success or failure
  73.  * logic since those cases are already available and subscribed to as
  74.  * custom events. You can still include callback.success and
  75.  * callback.failure, and they will be processed; but, it will also be
  76.  * a redundant action.
  77.  */
  78.  
  79. var transaction = YUC.asyncRequest('GET', sUrl, { timeout: 3000 });
  80.  
// 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:

  1. var callback = {
  2. customevents:{
  3. onStart: function(eventType, args) {
  4. // eventType has a string value of "startEvent".
  5. // args[0].tId is the integer transaction ID.
  6. // args[1] contains the value of <code>callback.argument</code>, if callback.argument is defined.
  7. },
  8. onComplete: function(eventType, args) {
  9. // eventType has a string value of "completeEvent".
  10. // args[0].tId is the integer transaction ID.
  11. // args[1] contains the value of <code>callback.argument</code>, if callback.argument is defined.
  12. },
  13. onSuccess: function(eventType, args) {
  14. /*
  15. * eventType has a string value of "successEvent".
  16. * args[0] is the response object, which has the
  17. * following properties:
  18. *
  19. * args[0].tId
  20. * args[0].status
  21. * args[0].statusText
  22. * args[0].getResponseHeader[ ]
  23. * args[0].getAllResponseHeaders
  24. * args[0].responseText
  25. * args[0].responseXML
  26. * args[0].argument
  27. */
  28. },
  29. onFailure: function(eventType, args) {
  30. // eventType has a string value of "failureEvent".
  31. // args[0] is the response object.
  32. },
  33.  
  34. // Define this event handler for file upload transactions *only*.
  35. // This handler will not be used for any other transaction cases.
  36. onUpload: function(eventType, args) {
  37. // eventType has a string value of "uploadEvent".
  38. // args[0] is the response object.
  39. },
  40. onAbort: function(eventType, args) {
  41. // eventType has a string value of "abortEvent".
  42. // args[0].tId is the integer transaction ID.
  43. // args[1] contains the value of <code>callback.argument</code>, if callback.argument is defined.
  44. }
  45. }
  46. };
  47.  
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:

  1. /*
  2.  * Create an event handler object to handle a transaction's custom events.
  3.  *
  4.  * NOTE: You can also choose to represent your event handlers as global
  5.  * functions instead of object members, and omit the scope argument from
  6.  * the callback.
  7.  *
  8.  * This example demonstrates a non-file upload transaction, hence the
  9.  * handler onUpload is not defined.
  10.  */
  11. var handleEvent = {
  12. start: function(eventType, args) {
  13. // do something when startEvent fires.
  14. },
  15.  
  16. complete: function(eventType, args) {
  17. // do something when completeEvent fires.
  18. },
  19.  
  20. success: function(eventType, args) {
  21. // do something when successEvent fires.
  22. },
  23.  
  24. failure: function(eventType, args) {
  25. // do something when failureEvent fires.
  26. },
  27.  
  28. abort: function(eventType, args) {
  29. // do something when abortEvent fires.
  30. }
  31. };
  32.  
  33. /*
  34.  * This example shows how to subscribe to all custom events.
  35.  * Pass the *handleEvent* object as the second argument to provide
  36.  * the necessary scope correction for any usage of the *this* keyword
  37.  * in any of the handler functions.
  38.  *
  39.  * NOTE: All events are subscribed in this example, but you can choose
  40.  * to subscribe to any combination of custom events desired. None are
  41.  * mandatory.
  42.  */
  43.  
  44. // Define the scope property with a value of *handleEvent* to provide
  45. // the necessary scope correction for any usage of the *this* keyword
  46. // in any of the handler functions.
  47.  
  48. /* Callback object with custom events defined */
  49. var callback = {
  50. customevents: {
  51. onStart: handleEvent.start,
  52. onComplete: handleEvent.complete,
  53. onSuccess: handleEvent.success,
  54. onFailure: handleEvent.failure,
  55. onAbort: handleEvent.abort
  56. },
  57. scope:handleEvent,
  58. argument: ["foo", "bar", "baz"]
  59. };
  60.  
  61. var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);
  62.  
/*
 * 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);
 

Using Request Signatures

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.

  1.  
  2. // $deleteRecordToken can be any additional, random sequence concatenated onto $username.
  3. // to salt the string which is converted to an MD5 hash.
  4. $transaction_signature = md5($username . $deleteRecordToken);
  5.  
 
// $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);
 
  1. /*
  2.  * Create a custom header -- in this case "X-Signature" -- using
  3.  * connection manager with the signature as its value, and initiate
  4.  * the transaction. The transaction is sent to "/delete_record.php".
  5.  */
  6. YAHOO.util.Connect.initHeader('X-Signature', '<? echo $transaction_signature ?>');
  7. var request = YAHOO.util.Connect.asyncRequest('GET', '/delete_record.php', callback);
  8.  
/*
 * 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.

  1.  
  2. $transaction_signature = md5($username . $deleteRecordToken);
  3.  
  4. if ($_SERVER['HTTP_X_SIGNATURE'] === $transaction_signature) {
  5. // proceed with delete operation
  6. // ...
  7. } else {
  8. // there is a problem
  9. // ...
  10. }
  11.  
  12.  
 
$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.

  1.  
  2. $transaction_signature = md5($username . $deleteRecordToken);
  3.  
  4. // $uri is the resource and the querystring includes the
  5. // signature.
  6. $uri = '/delete_record.php?signature=' . $transaction_signature;
  7.  
  8.  
 
$transaction_signature = md5($username . $deleteRecordToken);
 
// $uri is the resource and the querystring includes the
// signature.
$uri = '/delete_record.php?signature=' . $transaction_signature;
 
 
  1. var request = YAHOO.util.Connect.asyncRequest('GET', '<? echo $uri ?>', callback);
  2.  
var request = YAHOO.util.Connect.asyncRequest('GET', '<? echo $uri ?>', callback);
 

With POST requests, the signature is sent as part of the data.

  1.  
  2. $transaction_signature = md5($username . $updateRecordToken);
  3.  
  4.  
 
$transaction_signature = md5($username . $updateRecordToken);
 
 
  1. // postData represents the data sent in the POST request,
  2. // and the signature is sent as part of the POST message.
  3. var request = YAHOO.util.Connect.asyncRequest('POST', '/update_record.php', callback, postData +
  4. '&signature=<? echo $transaction_signature ?>');
  5.  
// 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 ?>');
 

Transaction Status

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.

  1. //Initiate an asynchronous transaction.
  2. var cObj = YAHOO.util.Connect.asyncRequest('GET','http://www.yahoo.com',callback);
  3.  
  4. //isCallInProgress will return true if the transaction has not been completed.
  5. var callStatus = YAHOO.util.Connect.isCallInProgress(cObj);
  6.  
//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.

  1. //Initiate an asynchronous transaction.
  2. var cObj = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);
  3.  
  4. //Abort the transaction if it isn't completed in ten seconds.
  5. setTimeout(function() { YAHOO.util.Connect.abort(cObj) },10000);
  6.  
//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.

  1. /*
  2.  * Abort the transaction if it isn't completed in ten seconds,
  3.  * and pass the callback with a defined failure handler as the
  4.  * second argument. The failure callback will receive a response
  5.  * object with properties as described in the abort subsection of
  6.  * Failure Case.
  7.  *
  8.  * abort() will return true if the transaction was successfully
  9.  * aborted. Otherwise, it will return false.
  10.  *
  11.  */
  12. setTimeout(function() { YAHOO.util.Connect.abort(cObj, callback) },10000);
  13.  
/*
 * 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);
 

Known Issues

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.

Support & Community

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.

Filing Bugs & Feature Requests

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.

Connection Manager Cheat Sheet:

Cheat Sheet
for Connection Manager.

Download full set of cheat sheets.

More Reading about the YUI Connection Manager:

YUI Connection Manager on del.icio.us:

Copyright © 2013 Yahoo! Inc. All rights reserved.

Privacy Policy - Copyright Policy - Job Openings