2 Copyright (c) 2011, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.com/yui/license.html
8 * The Connection Manager provides a simplified interface to the XMLHttpRequest
9 * object. It handles cross-browser instantiantion of XMLHttpRequest, negotiates the
10 * interactive states and server response, returning the results to a pre-defined
11 * callback you create.
13 * @namespace YAHOO.util
20 * The Connection Manager singleton provides methods for creating and managing
21 * asynchronous transactions.
23 * @class YAHOO.util.Connect
29 * @description Array of MSFT ActiveX ids for XMLHttpRequest.
30 * @property _msxml_progid
42 * @description Object literal of HTTP header(s)
43 * @property _http_header
51 * @description Determines if HTTP headers are set.
52 * @property _has_http_headers
57 _has_http_headers:false,
60 * @description Determines if a default header of
61 * Content-Type of 'application/x-www-form-urlencoded'
62 * will be added to any client HTTP headers sent for POST
64 * @property _use_default_post_header
69 _use_default_post_header:true,
72 * @description The default header used for POST transactions.
73 * @property _default_post_header
78 _default_post_header:'application/x-www-form-urlencoded; charset=UTF-8',
81 * @description The default header used for transactions involving the
83 * @property _default_form_header
88 _default_form_header:'application/x-www-form-urlencoded',
91 * @description Determines if a default header of
92 * 'X-Requested-With: XMLHttpRequest'
93 * will be added to each transaction.
94 * @property _use_default_xhr_header
99 _use_default_xhr_header:true,
102 * @description The default header value for the label
103 * "X-Requested-With". This is sent with each
104 * transaction, by default, to identify the
105 * request as being made by YUI Connection Manager.
106 * @property _default_xhr_header
111 _default_xhr_header:'XMLHttpRequest',
114 * @description Determines if custom, default headers
115 * are set for each transaction.
116 * @property _has_default_header
121 _has_default_headers:true,
124 * @description Property modified by setForm() to determine if the data
125 * should be submitted as an HTML form.
126 * @property _isFormSubmit
134 * @description Determines if custom, default headers
135 * are set for each transaction.
136 * @property _has_default_header
144 * @description Collection of polling references to the polling mechanism in handleReadyState.
153 * @description Queue of timeout values for each transaction callback with a defined timeout value.
162 * @description The polling frequency, in milliseconds, for HandleReadyState.
163 * when attempting to determine a transaction's XHR readyState.
164 * The default is 50 milliseconds.
165 * @property _polling_interval
170 _polling_interval:50,
173 * @description A transaction counter that increments the transaction id for each transaction.
174 * @property _transaction_id
182 * @description Custom event that fires at the start of a transaction
183 * @property startEvent
188 startEvent: new YAHOO.util.CustomEvent('start'),
191 * @description Custom event that fires when a transaction response has completed.
192 * @property completeEvent
197 completeEvent: new YAHOO.util.CustomEvent('complete'),
200 * @description Custom event that fires when handleTransactionResponse() determines a
201 * response in the HTTP 2xx range.
202 * @property successEvent
207 successEvent: new YAHOO.util.CustomEvent('success'),
210 * @description Custom event that fires when handleTransactionResponse() determines a
211 * response in the HTTP 4xx/5xx range.
212 * @property failureEvent
217 failureEvent: new YAHOO.util.CustomEvent('failure'),
220 * @description Custom event that fires when a transaction is successfully aborted.
221 * @property abortEvent
226 abortEvent: new YAHOO.util.CustomEvent('abort'),
229 * @description A reference table that maps callback custom events members to its specific
231 * @property _customEvents
238 onStart:['startEvent', 'start'],
239 onComplete:['completeEvent', 'complete'],
240 onSuccess:['successEvent', 'success'],
241 onFailure:['failureEvent', 'failure'],
242 onUpload:['uploadEvent', 'upload'],
243 onAbort:['abortEvent', 'abort']
247 * @description Member to add an ActiveX id to the existing xml_progid array.
248 * In the event(unlikely) a new ActiveX id is introduced, it can be added
249 * without internal code modifications.
253 * @param {string} id The ActiveX id to be added to initialize the XHR object.
256 setProgId:function(id)
258 this._msxml_progid.unshift(id);
262 * @description Member to override the default POST header.
263 * @method setDefaultPostHeader
266 * @param {boolean} b Set and use default header - true or false .
269 setDefaultPostHeader:function(b)
271 if(typeof b == 'string'){
272 this._default_post_header = b;
273 this._use_default_post_header = true;
276 else if(typeof b == 'boolean'){
277 this._use_default_post_header = b;
282 * @description Member to override the default transaction header..
283 * @method setDefaultXhrHeader
286 * @param {boolean} b Set and use default header - true or false .
289 setDefaultXhrHeader:function(b)
291 if(typeof b == 'string'){
292 this._default_xhr_header = b;
295 this._use_default_xhr_header = b;
300 * @description Member to modify the default polling interval.
301 * @method setPollingInterval
304 * @param {int} i The polling interval in milliseconds.
307 setPollingInterval:function(i)
309 if(typeof i == 'number' && isFinite(i)){
310 this._polling_interval = i;
315 * @description Instantiates a XMLHttpRequest object and returns an object with two properties:
316 * the XMLHttpRequest instance and the transaction id.
317 * @method createXhrObject
320 * @param {int} transactionId Property containing the transaction id for this transaction.
323 createXhrObject:function(transactionId)
328 // Instantiates XMLHttpRequest in non-IE browsers and assigns to http.
329 http = new XMLHttpRequest();
330 // Object literal with http and tId properties
331 obj = { conn:http, tId:transactionId, xhr: true };
335 for(i=0; i<this._msxml_progid.length; ++i){
338 // Instantiates XMLHttpRequest for IE and assign to http
339 http = new ActiveXObject(this._msxml_progid[i]);
340 // Object literal with conn and tId properties
341 obj = { conn:http, tId:transactionId, xhr: true };
354 * @description This method is called by asyncRequest to create a
355 * valid connection object for the transaction. It also passes a
356 * transaction id and increments the transaction id counter.
357 * @method getConnectionObject
362 getConnectionObject:function(t)
364 var o, tId = this._transaction_id;
369 o = this.createXhrObject(tId);
374 o.conn = this._transport;
377 else if(t==='upload'){
383 this._transaction_id++;
391 * @description Method for initiating an asynchronous request via the XHR object.
392 * @method asyncRequest
395 * @param {string} method HTTP transaction method
396 * @param {string} uri Fully qualified path of resource
397 * @param {callback} callback User-defined callback function or object
398 * @param {string} postData POST body
399 * @return {object} Returns the connection object
401 asyncRequest:function(method, uri, callback, postData)
403 var args = callback&&callback.argument?callback.argument:null,
407 if(this._isFileUpload){
410 else if(callback && callback.xdr){
414 o = this.getConnectionObject(t);
420 // Intialize any transaction-specific custom events, if provided.
421 if(callback && callback.customevents){
422 this.initCustomEvents(o, callback);
425 if(this._isFormSubmit){
426 if(this._isFileUpload){
427 window.setTimeout(function(){YCM.uploadFile(o, callback, uri, postData);}, 10);
431 // If the specified HTTP method is GET, setForm() will return an
432 // encoded string that is concatenated to the uri to
433 // create a querystring.
434 if(method.toUpperCase() == 'GET'){
435 if(this._sFormData.length !== 0){
436 // If the URI already contains a querystring, append an ampersand
437 // and then concatenate _sFormData to the URI.
438 uri += ((uri.indexOf('?') == -1)?'?':'&') + this._sFormData;
441 else if(method.toUpperCase() == 'POST'){
442 // If POST data exist in addition to the HTML form data,
443 // it will be concatenated to the form data.
444 postData = postData?this._sFormData + "&" + postData:this._sFormData;
448 if(method.toUpperCase() == 'GET' && (callback && callback.cache === false)){
449 // If callback.cache is defined and set to false, a
450 // timestamp value will be added to the querystring.
451 uri += ((uri.indexOf('?') == -1)?'?':'&') + "rnd=" + new Date().valueOf().toString();
454 // Each transaction will automatically include a custom header of
455 // "X-Requested-With: XMLHttpRequest" to identify the request as
456 // having originated from Connection Manager.
457 if(this._use_default_xhr_header){
458 if(!this._default_headers['X-Requested-With']){
459 this.initHeader('X-Requested-With', this._default_xhr_header, true);
463 //If the transaction method is POST and the POST header value is set to true
464 //or a custom value, initalize the Content-Type header to this value.
465 if((method.toUpperCase() === 'POST' && this._use_default_post_header) && this._isFormSubmit === false){
466 this.initHeader('Content-Type', this._default_post_header);
470 this.xdr(o, method, uri, callback, postData);
474 o.conn.open(method, uri, true);
475 //Initialize all default and custom HTTP headers,
476 if(this._has_default_headers || this._has_http_headers){
480 this.handleReadyState(o, callback);
481 o.conn.send(postData || '');
483 // Reset the HTML form data and state properties as
484 // soon as the data are submitted.
485 if(this._isFormSubmit === true){
486 this.resetFormState();
489 // Fire global custom event -- startEvent
490 this.startEvent.fire(o, args);
493 // Fire transaction custom event -- startEvent
494 o.startEvent.fire(o, args);
502 * @description This method creates and subscribes custom events,
503 * specific to each transaction
504 * @method initCustomEvents
507 * @param {object} o The connection object
508 * @param {callback} callback The user-defined callback object
511 initCustomEvents:function(o, callback)
514 // Enumerate through callback.customevents members and bind/subscribe
515 // events that match in the _customEvents table.
516 for(prop in callback.customevents){
517 if(this._customEvents[prop][0]){
518 // Create the custom event
519 o[this._customEvents[prop][0]] = new YAHOO.util.CustomEvent(this._customEvents[prop][1], (callback.scope)?callback.scope:null);
521 // Subscribe the custom event
522 o[this._customEvents[prop][0]].subscribe(callback.customevents[prop]);
528 * @description This method serves as a timer that polls the XHR object's readyState
529 * property during a transaction, instead of binding a callback to the
530 * onreadystatechange event. Upon readyState 4, handleTransactionResponse
531 * will process the response, and the timer will be cleared.
532 * @method handleReadyState
535 * @param {object} o The connection object
536 * @param {callback} callback The user-defined callback object
540 handleReadyState:function(o, callback)
544 args = (callback && callback.argument)?callback.argument:null;
546 if(callback && callback.timeout){
547 this._timeOut[o.tId] = window.setTimeout(function(){ oConn.abort(o, callback, true); }, callback.timeout);
550 this._poll[o.tId] = window.setInterval(
552 if(o.conn && o.conn.readyState === 4){
554 // Clear the polling interval for the transaction
555 // and remove the reference from _poll.
556 window.clearInterval(oConn._poll[o.tId]);
557 delete oConn._poll[o.tId];
559 if(callback && callback.timeout){
560 window.clearTimeout(oConn._timeOut[o.tId]);
561 delete oConn._timeOut[o.tId];
564 // Fire global custom event -- completeEvent
565 oConn.completeEvent.fire(o, args);
568 // Fire transaction custom event -- completeEvent
569 o.completeEvent.fire(o, args);
572 oConn.handleTransactionResponse(o, callback);
575 ,this._polling_interval);
579 * @description This method attempts to interpret the server response and
580 * determine whether the transaction was successful, or if an error or
581 * exception was encountered.
582 * @method handleTransactionResponse
585 * @param {object} o The connection object
586 * @param {object} callback The user-defined callback object
587 * @param {boolean} isAbort Determines if the transaction was terminated via abort().
590 handleTransactionResponse:function(o, callback, isAbort)
592 var httpStatus, responseObject,
593 args = (callback && callback.argument)?callback.argument:null,
594 xdrS = (o.r && o.r.statusText === 'xdr:success')?true:false,
595 xdrF = (o.r && o.r.statusText === 'xdr:failure')?true:false,
600 if((o.conn.status !== undefined && o.conn.status !== 0) || xdrS){
601 // XDR requests will not have HTTP status defined. The
602 // statusText property will define the response status
603 // set by the Flash transport.
604 httpStatus = o.conn.status;
606 else if(xdrF && !xdrA){
607 // Set XDR transaction failure to a status of 0, which
608 // resolves as an HTTP failure, instead of an exception.
617 // 13030 is a custom code to indicate the condition -- in Mozilla/FF --
618 // when the XHR object's status and statusText properties are
619 // unavailable, and a query attempt throws an exception.
623 if((httpStatus >= 200 && httpStatus < 300) || httpStatus === 1223 || xdrS){
624 responseObject = o.xdr ? o.r : this.createResponseObject(o, args);
625 if(callback && callback.success){
627 callback.success(responseObject);
630 // If a scope property is defined, the callback will be fired from
631 // the context of the object.
632 callback.success.apply(callback.scope, [responseObject]);
636 // Fire global custom event -- successEvent
637 this.successEvent.fire(responseObject);
640 // Fire transaction custom event -- successEvent
641 o.successEvent.fire(responseObject);
646 // The following cases are wininet.dll error codes that may be encountered.
647 case 12002: // Server timeout
648 case 12029: // 12029 to 12031 correspond to dropped connections.
651 case 12152: // Connection closed by server.
652 case 13030: // See above comments for variable status.
653 // XDR transactions will not resolve to this case, since the
654 // response object is already built in the xdr response.
655 responseObject = this.createExceptionObject(o.tId, args, (isAbort?isAbort:false));
656 if(callback && callback.failure){
658 callback.failure(responseObject);
661 callback.failure.apply(callback.scope, [responseObject]);
667 responseObject = (o.xdr) ? o.response : this.createResponseObject(o, args);
668 if(callback && callback.failure){
670 callback.failure(responseObject);
673 callback.failure.apply(callback.scope, [responseObject]);
678 // Fire global custom event -- failureEvent
679 this.failureEvent.fire(responseObject);
682 // Fire transaction custom event -- failureEvent
683 o.failureEvent.fire(responseObject);
688 this.releaseObject(o);
689 responseObject = null;
693 * @description This method evaluates the server response, creates and returns the results via
694 * its properties. Success and failure cases will differ in the response
695 * object's property values.
696 * @method createResponseObject
699 * @param {object} o The connection object
700 * @param {callbackArg} callbackArg The user-defined argument or arguments to be passed to the callback
703 createResponseObject:function(o, callbackArg)
705 var obj = {}, headerObj = {},
706 i, headerStr, header, delimitPos;
710 headerStr = o.conn.getAllResponseHeaders();
711 header = headerStr.split('\n');
712 for(i=0; i<header.length; i++){
713 delimitPos = header[i].indexOf(':');
714 if(delimitPos != -1){
715 headerObj[header[i].substring(0,delimitPos)] = YAHOO.lang.trim(header[i].substring(delimitPos+2));
722 // Normalize IE's response to HTTP 204 when Win error 1223.
723 obj.status = (o.conn.status == 1223)?204:o.conn.status;
724 // Normalize IE's statusText to "No Content" instead of "Unknown".
725 obj.statusText = (o.conn.status == 1223)?"No Content":o.conn.statusText;
726 obj.getResponseHeader = headerObj;
727 obj.getAllResponseHeaders = headerStr;
728 obj.responseText = o.conn.responseText;
729 obj.responseXML = o.conn.responseXML;
732 obj.argument = callbackArg;
739 * @description If a transaction cannot be completed due to dropped or closed connections,
740 * there may be not be enough information to build a full response object.
741 * The failure callback will be fired and this specific condition can be identified
742 * by a status property value of 0.
744 * If an abort was successful, the status property will report a value of -1.
746 * @method createExceptionObject
749 * @param {int} tId The Transaction Id
750 * @param {callbackArg} callbackArg The user-defined argument or arguments to be passed to the callback
751 * @param {boolean} isAbort Determines if the exception case is caused by a transaction abort
754 createExceptionObject:function(tId, callbackArg, isAbort)
757 COMM_ERROR = 'communication failure',
759 ABORT_ERROR = 'transaction aborted',
764 obj.status = ABORT_CODE;
765 obj.statusText = ABORT_ERROR;
768 obj.status = COMM_CODE;
769 obj.statusText = COMM_ERROR;
773 obj.argument = callbackArg;
780 * @description Method that initializes the custom HTTP headers for the each transaction.
784 * @param {string} label The HTTP header label
785 * @param {string} value The HTTP header value
786 * @param {string} isDefault Determines if the specific header is a default header
787 * automatically sent with each transaction.
790 initHeader:function(label, value, isDefault)
792 var headerObj = (isDefault)?this._default_headers:this._http_headers;
794 headerObj[label] = value;
796 this._has_default_headers = true;
799 this._has_http_headers = true;
805 * @description Accessor that sets the HTTP headers for each transaction.
809 * @param {object} o The connection object for the transaction.
812 setHeader:function(o)
815 if(this._has_default_headers){
816 for(prop in this._default_headers){
817 if(YAHOO.lang.hasOwnProperty(this._default_headers, prop)){
818 o.conn.setRequestHeader(prop, this._default_headers[prop]);
823 if(this._has_http_headers){
824 for(prop in this._http_headers){
825 if(YAHOO.lang.hasOwnProperty(this._http_headers, prop)){
826 o.conn.setRequestHeader(prop, this._http_headers[prop]);
830 this._http_headers = {};
831 this._has_http_headers = false;
836 * @description Resets the default HTTP headers object
837 * @method resetDefaultHeaders
842 resetDefaultHeaders:function(){
843 this._default_headers = {};
844 this._has_default_headers = false;
848 * @description Method to terminate a transaction, if it has not reached readyState 4.
852 * @param {object} o The connection object returned by asyncRequest.
853 * @param {object} callback User-defined callback object.
854 * @param {string} isTimeout boolean to indicate if abort resulted from a callback timeout.
857 abort:function(o, callback, isTimeout)
860 args = (callback && callback.argument)?callback.argument:null;
865 if(this.isCallInProgress(o)){
866 // Issue abort request
869 window.clearInterval(this._poll[o.tId]);
870 delete this._poll[o.tId];
873 window.clearTimeout(this._timeOut[o.tId]);
874 delete this._timeOut[o.tId];
886 var frameId = 'yuiIO' + o.tId;
887 var io = document.getElementById(frameId);
890 // Remove all listeners on the iframe prior to
892 YAHOO.util.Event.removeListener(io, "load");
893 // Destroy the iframe facilitating the transaction.
894 document.body.removeChild(io);
897 window.clearTimeout(this._timeOut[o.tId]);
898 delete this._timeOut[o.tId];
908 if(abortStatus === true){
909 // Fire global custom event -- abortEvent
910 this.abortEvent.fire(o, args);
913 // Fire transaction custom event -- abortEvent
914 o.abortEvent.fire(o, args);
917 this.handleTransactionResponse(o, callback, true);
924 * @description Determines if the transaction is still being processed.
925 * @method isCallInProgress
928 * @param {object} o The connection object returned by asyncRequest
931 isCallInProgress:function(o)
934 // if the XHR object assigned to the transaction has not been dereferenced,
935 // then check its readyState status. Otherwise, return false.
937 return o.conn.readyState !== 4 && o.conn.readyState !== 0;
939 else if(o.xdr && o.conn){
940 return o.conn.isCallInProgress(o.tId);
942 else if(o.upload === true){
943 return document.getElementById('yuiIO' + o.tId)?true:false;
951 * @description Dereference the XHR instance and the connection object after the transaction is completed.
952 * @method releaseObject
955 * @param {object} o The connection object
958 releaseObject:function(o)
961 //dereference the XHR instance.
965 //dereference the connection object.
971 YAHOO.register("connection_core", YAHOO.util.Connect, {version: "2.9.0", build: "2800"});