2 Copyright (c) 2009, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.net/yui/license.txt
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.
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 Determines if custom, default headers
125 * are set for each transaction.
126 * @property _has_default_header
134 * @description Collection of polling references to the polling mechanism in handleReadyState.
143 * @description Queue of timeout values for each transaction callback with a defined timeout value.
152 * @description The polling frequency, in milliseconds, for HandleReadyState.
153 * when attempting to determine a transaction's XHR readyState.
154 * The default is 50 milliseconds.
155 * @property _polling_interval
160 _polling_interval:50,
163 * @description A transaction counter that increments the transaction id for each transaction.
164 * @property _transaction_id
172 * @description Custom event that fires at the start of a transaction
173 * @property startEvent
178 startEvent: new YAHOO.util.CustomEvent('start'),
181 * @description Custom event that fires when a transaction response has completed.
182 * @property completeEvent
187 completeEvent: new YAHOO.util.CustomEvent('complete'),
190 * @description Custom event that fires when handleTransactionResponse() determines a
191 * response in the HTTP 2xx range.
192 * @property successEvent
197 successEvent: new YAHOO.util.CustomEvent('success'),
200 * @description Custom event that fires when handleTransactionResponse() determines a
201 * response in the HTTP 4xx/5xx range.
202 * @property failureEvent
207 failureEvent: new YAHOO.util.CustomEvent('failure'),
210 * @description Custom event that fires when a transaction is successfully aborted.
211 * @property abortEvent
216 abortEvent: new YAHOO.util.CustomEvent('abort'),
219 * @description A reference table that maps callback custom events members to its specific
221 * @property _customEvents
228 onStart:['startEvent', 'start'],
229 onComplete:['completeEvent', 'complete'],
230 onSuccess:['successEvent', 'success'],
231 onFailure:['failureEvent', 'failure'],
232 onUpload:['uploadEvent', 'upload'],
233 onAbort:['abortEvent', 'abort']
237 * @description Member to add an ActiveX id to the existing xml_progid array.
238 * In the event(unlikely) a new ActiveX id is introduced, it can be added
239 * without internal code modifications.
243 * @param {string} id The ActiveX id to be added to initialize the XHR object.
246 setProgId:function(id)
248 this._msxml_progid.unshift(id);
249 YAHOO.log('ActiveX Program Id ' + id + ' added to _msxml_progid.', 'info', 'Connection');
253 * @description Member to override the default POST header.
254 * @method setDefaultPostHeader
257 * @param {boolean} b Set and use default header - true or false .
260 setDefaultPostHeader:function(b)
262 if(typeof b == 'string'){
263 this._default_post_header = b;
264 YAHOO.log('Default POST header set to ' + b, 'info', 'Connection');
266 else if(typeof b == 'boolean'){
267 this._use_default_post_header = b;
272 * @description Member to override the default transaction header..
273 * @method setDefaultXhrHeader
276 * @param {boolean} b Set and use default header - true or false .
279 setDefaultXhrHeader:function(b)
281 if(typeof b == 'string'){
282 this._default_xhr_header = b;
283 YAHOO.log('Default XHR header set to ' + b, 'info', 'Connection');
286 this._use_default_xhr_header = b;
291 * @description Member to modify the default polling interval.
292 * @method setPollingInterval
295 * @param {int} i The polling interval in milliseconds.
298 setPollingInterval:function(i)
300 if(typeof i == 'number' && isFinite(i)){
301 this._polling_interval = i;
302 YAHOO.log('Default polling interval set to ' + i +'ms', 'info', 'Connection');
307 * @description Instantiates a XMLHttpRequest object and returns an object with two properties:
308 * the XMLHttpRequest instance and the transaction id.
309 * @method createXhrObject
312 * @param {int} transactionId Property containing the transaction id for this transaction.
315 createXhrObject:function(transactionId)
320 // Instantiates XMLHttpRequest in non-IE browsers and assigns to http.
321 http = new XMLHttpRequest();
322 // Object literal with http and tId properties
323 obj = { conn:http, tId:transactionId, xhr: true };
324 YAHOO.log('XHR object created for transaction ' + transactionId, 'info', 'Connection');
328 for(i=0; i<this._msxml_progid.length; ++i){
331 // Instantiates XMLHttpRequest for IE and assign to http
332 http = new ActiveXObject(this._msxml_progid[i]);
333 // Object literal with conn and tId properties
334 obj = { conn:http, tId:transactionId, xhr: true };
335 YAHOO.log('ActiveX XHR object created for transaction ' + transactionId, 'info', 'Connection');
348 * @description This method is called by asyncRequest to create a
349 * valid connection object for the transaction. It also passes a
350 * transaction id and increments the transaction id counter.
351 * @method getConnectionObject
356 getConnectionObject:function(t)
358 var o, tId = this._transaction_id;
363 o = this.createXhrObject(tId);
368 o.conn = this._transport;
371 else if(t==='upload'){
377 this._transaction_id++;
385 * @description Method for initiating an asynchronous request via the XHR object.
386 * @method asyncRequest
389 * @param {string} method HTTP transaction method
390 * @param {string} uri Fully qualified path of resource
391 * @param {callback} callback User-defined callback function or object
392 * @param {string} postData POST body
393 * @return {object} Returns the connection object
395 asyncRequest:function(method, uri, callback, postData)
397 var o,t,args = (callback && callback.argument)?callback.argument:null;
399 if(this._isFileUpload){
402 else if(callback.xdr){
406 o = this.getConnectionObject(t);
408 YAHOO.log('Unable to create connection object.', 'error', 'Connection');
413 // Intialize any transaction-specific custom events, if provided.
414 if(callback && callback.customevents){
415 this.initCustomEvents(o, callback);
418 if(this._isFormSubmit){
419 if(this._isFileUpload){
420 this.uploadFile(o, callback, uri, postData);
424 // If the specified HTTP method is GET, setForm() will return an
425 // encoded string that is concatenated to the uri to
426 // create a querystring.
427 if(method.toUpperCase() == 'GET'){
428 if(this._sFormData.length !== 0){
429 // If the URI already contains a querystring, append an ampersand
430 // and then concatenate _sFormData to the URI.
431 uri += ((uri.indexOf('?') == -1)?'?':'&') + this._sFormData;
434 else if(method.toUpperCase() == 'POST'){
435 // If POST data exist in addition to the HTML form data,
436 // it will be concatenated to the form data.
437 postData = postData?this._sFormData + "&" + postData:this._sFormData;
441 if(method.toUpperCase() == 'GET' && (callback && callback.cache === false)){
442 // If callback.cache is defined and set to false, a
443 // timestamp value will be added to the querystring.
444 uri += ((uri.indexOf('?') == -1)?'?':'&') + "rnd=" + new Date().valueOf().toString();
447 // Each transaction will automatically include a custom header of
448 // "X-Requested-With: XMLHttpRequest" to identify the request as
449 // having originated from Connection Manager.
450 if(this._use_default_xhr_header){
451 if(!this._default_headers['X-Requested-With']){
452 this.initHeader('X-Requested-With', this._default_xhr_header, true);
453 YAHOO.log('Initialize transaction header X-Request-Header to XMLHttpRequest.', 'info', 'Connection');
457 //If the transaction method is POST and the POST header value is set to true
458 //or a custom value, initalize the Content-Type header to this value.
459 if((method.toUpperCase() === 'POST' && this._use_default_post_header) && this._isFormSubmit === false){
460 this.initHeader('Content-Type', this._default_post_header);
461 YAHOO.log('Initialize header Content-Type to application/x-www-form-urlencoded; UTF-8 for POST transaction.', 'info', 'Connection');
465 this.xdr(o, method, uri, callback, postData);
469 o.conn.open(method, uri, true);
470 //Initialize all default and custom HTTP headers,
471 if(this._has_default_headers || this._has_http_headers){
475 this.handleReadyState(o, callback);
476 o.conn.send(postData || '');
477 YAHOO.log('Transaction ' + o.tId + ' sent.', 'info', 'Connection');
479 // Reset the HTML form data and state properties as
480 // soon as the data are submitted.
481 if(this._isFormSubmit === true){
482 this.resetFormState();
485 // Fire global custom event -- startEvent
486 this.startEvent.fire(o, args);
489 // Fire transaction custom event -- startEvent
490 o.startEvent.fire(o, args);
498 * @description This method creates and subscribes custom events,
499 * specific to each transaction
500 * @method initCustomEvents
503 * @param {object} o The connection object
504 * @param {callback} callback The user-defined callback object
507 initCustomEvents:function(o, callback)
510 // Enumerate through callback.customevents members and bind/subscribe
511 // events that match in the _customEvents table.
512 for(prop in callback.customevents){
513 if(this._customEvents[prop][0]){
514 // Create the custom event
515 o[this._customEvents[prop][0]] = new YAHOO.util.CustomEvent(this._customEvents[prop][1], (callback.scope)?callback.scope:null);
516 YAHOO.log('Transaction-specific Custom Event ' + o[this._customEvents[prop][1]] + ' created.', 'info', 'Connection');
518 // Subscribe the custom event
519 o[this._customEvents[prop][0]].subscribe(callback.customevents[prop]);
520 YAHOO.log('Transaction-specific Custom Event ' + o[this._customEvents[prop][1]] + ' subscribed.', 'info', 'Connection');
526 * @description This method serves as a timer that polls the XHR object's readyState
527 * property during a transaction, instead of binding a callback to the
528 * onreadystatechange event. Upon readyState 4, handleTransactionResponse
529 * will process the response, and the timer will be cleared.
530 * @method handleReadyState
533 * @param {object} o The connection object
534 * @param {callback} callback The user-defined callback object
538 handleReadyState:function(o, callback)
542 args = (callback && callback.argument)?callback.argument:null;
544 if(callback && callback.timeout){
545 this._timeOut[o.tId] = window.setTimeout(function(){ oConn.abort(o, callback, true); }, callback.timeout);
548 this._poll[o.tId] = window.setInterval(
550 if(o.conn && o.conn.readyState === 4){
552 // Clear the polling interval for the transaction
553 // and remove the reference from _poll.
554 window.clearInterval(oConn._poll[o.tId]);
555 delete oConn._poll[o.tId];
557 if(callback && callback.timeout){
558 window.clearTimeout(oConn._timeOut[o.tId]);
559 delete oConn._timeOut[o.tId];
562 // Fire global custom event -- completeEvent
563 oConn.completeEvent.fire(o, args);
566 // Fire transaction custom event -- completeEvent
567 o.completeEvent.fire(o, args);
570 oConn.handleTransactionResponse(o, callback);
573 ,this._polling_interval);
577 * @description This method attempts to interpret the server response and
578 * determine whether the transaction was successful, or if an error or
579 * exception was encountered.
580 * @method handleTransactionResponse
583 * @param {object} o The connection object
584 * @param {object} callback The user-defined callback object
585 * @param {boolean} isAbort Determines if the transaction was terminated via abort().
588 handleTransactionResponse:function(o, callback, isAbort)
590 var httpStatus, responseObject,
591 args = (callback && callback.argument)?callback.argument:null,
592 xdrS = (o.r && o.r.statusText === 'xdr:success')?true:false,
593 xdrF = (o.r && o.r.statusText === 'xdr:failure')?true:false,
598 if((o.conn.status !== undefined && o.conn.status !== 0) || xdrS){
599 // XDR requests will not have HTTP status defined. The
600 // statusText property will define the response status
601 // set by the Flash transport.
602 httpStatus = o.conn.status;
604 else if(xdrF && !xdrA){
605 // Set XDR transaction failure to a status of 0, which
606 // resolves as an HTTP failure, instead of an exception.
615 // 13030 is a custom code to indicate the condition -- in Mozilla/FF --
616 // when the XHR object's status and statusText properties are
617 // unavailable, and a query attempt throws an exception.
621 if((httpStatus >= 200 && httpStatus < 300) || httpStatus === 1223 || xdrS){
622 responseObject = o.xdr ? o.r : this.createResponseObject(o, args);
623 if(callback && callback.success){
625 callback.success(responseObject);
626 YAHOO.log('Success callback. HTTP code is ' + httpStatus, 'info', 'Connection');
629 // If a scope property is defined, the callback will be fired from
630 // the context of the object.
631 callback.success.apply(callback.scope, [responseObject]);
632 YAHOO.log('Success callback with scope. HTTP code is ' + httpStatus, 'info', 'Connection');
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);
659 YAHOO.log('Failure callback. Exception detected. Status code is ' + httpStatus, 'warn', 'Connection');
662 callback.failure.apply(callback.scope, [responseObject]);
663 YAHOO.log('Failure callback with scope. Exception detected. Status code is ' + httpStatus, 'warn', 'Connection');
669 responseObject = (o.xdr) ? o.response : this.createResponseObject(o, args);
670 if(callback && callback.failure){
672 callback.failure(responseObject);
673 YAHOO.log('Failure callback. HTTP status code is ' + httpStatus, 'warn', 'Connection');
676 callback.failure.apply(callback.scope, [responseObject]);
677 YAHOO.log('Failure callback with scope. HTTP status code is ' + httpStatus, 'warn', 'Connection');
682 // Fire global custom event -- failureEvent
683 this.failureEvent.fire(responseObject);
686 // Fire transaction custom event -- failureEvent
687 o.failureEvent.fire(responseObject);
692 this.releaseObject(o);
693 responseObject = null;
697 * @description This method evaluates the server response, creates and returns the results via
698 * its properties. Success and failure cases will differ in the response
699 * object's property values.
700 * @method createResponseObject
703 * @param {object} o The connection object
704 * @param {callbackArg} callbackArg The user-defined argument or arguments to be passed to the callback
707 createResponseObject:function(o, callbackArg)
709 var obj = {}, headerObj = {},
710 i, headerStr, header, delimitPos;
714 headerStr = o.conn.getAllResponseHeaders();
715 header = headerStr.split('\n');
716 for(i=0; i<header.length; i++){
717 delimitPos = header[i].indexOf(':');
718 if(delimitPos != -1){
719 headerObj[header[i].substring(0,delimitPos)] = YAHOO.lang.trim(header[i].substring(delimitPos+2));
726 // Normalize IE's response to HTTP 204 when Win error 1223.
727 obj.status = (o.conn.status == 1223)?204:o.conn.status;
728 // Normalize IE's statusText to "No Content" instead of "Unknown".
729 obj.statusText = (o.conn.status == 1223)?"No Content":o.conn.statusText;
730 obj.getResponseHeader = headerObj;
731 obj.getAllResponseHeaders = headerStr;
732 obj.responseText = o.conn.responseText;
733 obj.responseXML = o.conn.responseXML;
736 obj.argument = callbackArg;
743 * @description If a transaction cannot be completed due to dropped or closed connections,
744 * there may be not be enough information to build a full response object.
745 * The failure callback will be fired and this specific condition can be identified
746 * by a status property value of 0.
748 * If an abort was successful, the status property will report a value of -1.
750 * @method createExceptionObject
753 * @param {int} tId The Transaction Id
754 * @param {callbackArg} callbackArg The user-defined argument or arguments to be passed to the callback
755 * @param {boolean} isAbort Determines if the exception case is caused by a transaction abort
758 createExceptionObject:function(tId, callbackArg, isAbort)
761 COMM_ERROR = 'communication failure',
763 ABORT_ERROR = 'transaction aborted',
768 obj.status = ABORT_CODE;
769 obj.statusText = ABORT_ERROR;
772 obj.status = COMM_CODE;
773 obj.statusText = COMM_ERROR;
777 obj.argument = callbackArg;
784 * @description Method that initializes the custom HTTP headers for the each transaction.
788 * @param {string} label The HTTP header label
789 * @param {string} value The HTTP header value
790 * @param {string} isDefault Determines if the specific header is a default header
791 * automatically sent with each transaction.
794 initHeader:function(label, value, isDefault)
796 var headerObj = (isDefault)?this._default_headers:this._http_headers;
798 headerObj[label] = value;
800 this._has_default_headers = true;
803 this._has_http_headers = true;
809 * @description Accessor that sets the HTTP headers for each transaction.
813 * @param {object} o The connection object for the transaction.
816 setHeader:function(o)
819 if(this._has_default_headers){
820 for(prop in this._default_headers){
821 if(YAHOO.lang.hasOwnProperty(this._default_headers, prop)){
822 o.conn.setRequestHeader(prop, this._default_headers[prop]);
823 YAHOO.log('Default HTTP header ' + prop + ' set with value of ' + this._default_headers[prop], 'info', 'Connection');
828 if(this._has_http_headers){
829 for(prop in this._http_headers){
830 if(YAHOO.lang.hasOwnProperty(this._http_headers, prop)){
831 o.conn.setRequestHeader(prop, this._http_headers[prop]);
832 YAHOO.log('HTTP header ' + prop + ' set with value of ' + this._http_headers[prop], 'info', 'Connection');
836 this._http_headers = {};
837 this._has_http_headers = false;
842 * @description Resets the default HTTP headers object
843 * @method resetDefaultHeaders
848 resetDefaultHeaders:function(){
849 this._default_headers = {};
850 this._has_default_headers = false;
854 * @description Method to terminate a transaction, if it has not reached readyState 4.
858 * @param {object} o The connection object returned by asyncRequest.
859 * @param {object} callback User-defined callback object.
860 * @param {string} isTimeout boolean to indicate if abort resulted from a callback timeout.
863 abort:function(o, callback, isTimeout)
866 args = (callback && callback.argument)?callback.argument:null;
871 if(this.isCallInProgress(o)){
872 // Issue abort request
875 window.clearInterval(this._poll[o.tId]);
876 delete this._poll[o.tId];
879 window.clearTimeout(this._timeOut[o.tId]);
880 delete this._timeOut[o.tId];
892 var frameId = 'yuiIO' + o.tId;
893 var io = document.getElementById(frameId);
896 // Remove all listeners on the iframe prior to
898 YAHOO.util.Event.removeListener(io, "load");
899 // Destroy the iframe facilitating the transaction.
900 document.body.removeChild(io);
901 YAHOO.log('File upload iframe destroyed. Id is:' + frameId, 'info', 'Connection');
904 window.clearTimeout(this._timeOut[o.tId]);
905 delete this._timeOut[o.tId];
915 if(abortStatus === true){
916 // Fire global custom event -- abortEvent
917 this.abortEvent.fire(o, args);
920 // Fire transaction custom event -- abortEvent
921 o.abortEvent.fire(o, args);
924 this.handleTransactionResponse(o, callback, true);
925 YAHOO.log('Transaction ' + o.tId + ' aborted.', 'info', 'Connection');
932 * @description Determines if the transaction is still being processed.
933 * @method isCallInProgress
936 * @param {object} o The connection object returned by asyncRequest
939 isCallInProgress:function(o)
942 // if the XHR object assigned to the transaction has not been dereferenced,
943 // then check its readyState status. Otherwise, return false.
945 return o.conn.readyState !== 4 && o.conn.readyState !== 0;
947 else if(o.xdr && o.conn){
948 return o.conn.isCallInProgress(o.tId);
950 else if(o.upload === true){
951 return document.getElementById('yuiIO' + o.tId)?true:false;
959 * @description Dereference the XHR instance and the connection object after the transaction is completed.
960 * @method releaseObject
963 * @param {object} o The connection object
966 releaseObject:function(o)
969 //dereference the XHR instance.
972 YAHOO.log('Connection object for transaction ' + o.tId + ' destroyed.', 'info', 'Connection');
974 //dereference the connection object.
980 YAHOO.register("connection_core", YAHOO.util.Connect, {version: "2.8.0r4", build: "2449"});