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.
972 * @for YAHOO.util.Connect
975 var YCM = YAHOO.util.Connect, _fn = {};
978 * @description This method creates and instantiates the Flash transport.
982 * @param {string} URI to connection.swf.
986 var o = '<object id="YUIConnectionSwf" type="application/x-shockwave-flash" data="' +
987 uri + '" width="0" height="0">' +
988 '<param name="movie" value="' + uri + '">' +
989 '<param name="allowScriptAccess" value="always">' +
991 c = document.createElement('div');
993 document.body.appendChild(c);
998 * @description This method calls the public method on the
999 * Flash transport to start the XDR transaction. It is analogous
1000 * to Connection Manager's asyncRequest method.
1004 * @param {object} The transaction object.
1005 * @param {string} HTTP request method.
1006 * @param {string} URI for the transaction.
1007 * @param {object} The transaction's callback object.
1008 * @param {object} The JSON object used as HTTP POST data.
1011 function _xdr(o, m, u, c, d) {
1012 _fn[parseInt(o.tId)] = { 'o':o, 'c':c };
1018 o.conn.send(u, c, o.tId);
1022 * @description This method instantiates the Flash transport and
1023 * establishes a static reference to it, used for all XDR requests.
1027 * @param {string} URI to connection.swf.
1030 function _init(uri) {
1032 YCM._transport = document.getElementById('YUIConnectionSwf');
1035 function _xdrReady() {
1036 YCM.xdrReadyEvent.fire();
1040 * @description This method fires the global and transaction start
1045 * @param {object} The transaction object.
1046 * @param {string} The transaction's callback object.
1049 function _xdrStart(o, cb) {
1051 // Fire global custom event -- startEvent
1052 YCM.startEvent.fire(o, cb.argument);
1055 // Fire transaction custom event -- startEvent
1056 o.startEvent.fire(o, cb.argument);
1062 * @description This method is the initial response handler
1063 * for XDR transactions. The Flash transport calls this
1064 * function and sends the response payload.
1065 * @method handleXdrResponse
1068 * @param {object} The response object sent from the Flash transport.
1071 function _handleXdrResponse(r) {
1072 var o = _fn[r.tId].o,
1075 if (r.statusText === 'xdr:start') {
1080 r.responseText = decodeURI(r.responseText);
1083 o.r.argument = cb.argument;
1086 this.handleTransactionResponse(o, cb, r.statusText === 'xdr:abort' ? true : false);
1090 // Bind the functions to Connection Manager as static fields.
1093 YCM.transport = _init;
1094 YCM.xdrReadyEvent = new YAHOO.util.CustomEvent('xdrReady');
1095 YCM.xdrReady = _xdrReady;
1096 YCM.handleXdrResponse = _handleXdrResponse;
1100 * @for YAHOO.util.Connect
1103 var YCM = YAHOO.util.Connect,
1104 YE = YAHOO.util.Event,
1105 dM = document.documentMode ? document.documentMode : false;
1108 * @description Property modified by setForm() to determine if a file(s)
1109 * upload is expected.
1110 * @property _isFileUpload
1115 YCM._isFileUpload = false;
1118 * @description Property modified by setForm() to set a reference to the HTML
1119 * form node if the desired action is file upload.
1120 * @property _formNode
1125 YCM._formNode = null;
1128 * @description Property modified by setForm() to set the HTML form data
1129 * for each transaction.
1130 * @property _sFormData
1135 YCM._sFormData = null;
1138 * @description Tracks the name-value pair of the "clicked" submit button if multiple submit
1139 * buttons are present in an HTML form; and, if YAHOO.util.Event is available.
1140 * @property _submitElementValue
1145 YCM._submitElementValue = null;
1148 * @description Custom event that fires when handleTransactionResponse() determines a
1149 * response in the HTTP 4xx/5xx range.
1150 * @property failureEvent
1155 YCM.uploadEvent = new YAHOO.util.CustomEvent('upload');
1158 * @description Determines whether YAHOO.util.Event is available and returns true or false.
1159 * If true, an event listener is bound at the document level to trap click events that
1160 * resolve to a target type of "Submit". This listener will enable setForm() to determine
1161 * the clicked "Submit" value in a multi-Submit button, HTML form.
1162 * @property _hasSubmitListener
1166 YCM._hasSubmitListener = function() {
1172 var obj = YE.getTarget(e),
1173 name = obj.nodeName.toLowerCase();
1175 if((name === 'input' || name === 'button') && (obj.type && obj.type.toLowerCase() == 'submit')){
1176 YCM._submitElementValue = encodeURIComponent(obj.name) + "=" + encodeURIComponent(obj.value);
1185 * @description This method assembles the form label and value pairs and
1186 * constructs an encoded string.
1187 * asyncRequest() will automatically initialize the transaction with a
1188 * a HTTP header Content-Type of application/x-www-form-urlencoded.
1192 * @param {string || object} form id or name attribute, or form object.
1193 * @param {boolean} optional enable file upload.
1194 * @param {boolean} optional enable file upload over SSL in IE only.
1195 * @return {string} string of the HTML form field name and value pairs..
1197 function _setForm(formId, isUpload, secureUri)
1199 var oForm, oElement, oName, oValue, oDisabled,
1201 data = [], item = 0,
1204 this.resetFormState();
1206 if(typeof formId == 'string'){
1207 // Determine if the argument is a form id or a form name.
1208 // Note form name usage is deprecated by supported
1209 // here for legacy reasons.
1210 oForm = (document.getElementById(formId) || document.forms[formId]);
1212 else if(typeof formId == 'object'){
1213 // Treat argument as an HTML form object.
1220 // If the isUpload argument is true, setForm will call createFrame to initialize
1221 // an iframe as the form target.
1223 // The argument secureURI is also required by IE in SSL environments
1224 // where the secureURI string is a fully qualified HTTP path, used to set the source
1225 // of the iframe, to a stub resource in the same domain.
1228 // Create iframe in preparation for file upload.
1229 this.createFrame(secureUri?secureUri:null);
1231 // Set form reference and file upload properties to true.
1232 this._isFormSubmit = true;
1233 this._isFileUpload = true;
1234 this._formNode = oForm;
1239 // Iterate over the form elements collection to construct the
1240 // label-value pairs.
1241 for (i=0,len=oForm.elements.length; i<len; ++i){
1242 oElement = oForm.elements[i];
1243 oDisabled = oElement.disabled;
1244 oName = oElement.name;
1246 // Do not submit fields that are disabled or
1247 // do not have a name attribute value.
1248 if(!oDisabled && oName)
1250 oName = encodeURIComponent(oName)+'=';
1251 oValue = encodeURIComponent(oElement.value);
1253 switch(oElement.type)
1255 // Safari, Opera, FF all default opt.value from .text if
1256 // value attribute not specified in markup
1258 if (oElement.selectedIndex > -1) {
1259 opt = oElement.options[oElement.selectedIndex];
1260 data[item++] = oName + encodeURIComponent(
1261 (opt.attributes.value && opt.attributes.value.specified) ? opt.value : opt.text);
1264 case 'select-multiple':
1265 if (oElement.selectedIndex > -1) {
1266 for(j=oElement.selectedIndex, jlen=oElement.options.length; j<jlen; ++j){
1267 opt = oElement.options[j];
1269 data[item++] = oName + encodeURIComponent(
1270 (opt.attributes.value && opt.attributes.value.specified) ? opt.value : opt.text);
1277 if(oElement.checked){
1278 data[item++] = oName + oValue;
1282 // stub case as XMLHttpRequest will only send the file path as a string.
1284 // stub case for fieldset element which returns undefined.
1286 // stub case for input type reset button.
1288 // stub case for input type button elements.
1291 if(hasSubmit === false){
1292 if(this._hasSubmitListener && this._submitElementValue){
1293 data[item++] = this._submitElementValue;
1299 data[item++] = oName + oValue;
1304 this._isFormSubmit = true;
1305 this._sFormData = data.join('&');
1308 this.initHeader('Content-Type', this._default_form_header);
1310 return this._sFormData;
1314 * @description Resets HTML form properties when an HTML form or HTML form
1315 * with file upload transaction is sent.
1316 * @method resetFormState
1321 function _resetFormState(){
1322 this._isFormSubmit = false;
1323 this._isFileUpload = false;
1324 this._formNode = null;
1325 this._sFormData = "";
1330 * @description Creates an iframe to be used for form file uploads. It is remove from the
1331 * document upon completion of the upload transaction.
1332 * @method createFrame
1335 * @param {string} optional qualified path of iframe resource for SSL in IE.
1338 function _createFrame(secureUri){
1340 // IE does not allow the setting of id and name attributes as object
1341 // properties via createElement(). A different iframe creation
1342 // pattern is required for IE.
1343 var frameId = 'yuiIO' + this._transaction_id,
1344 ie9 = (dM === 9) ? true : false,
1347 if(YAHOO.env.ua.ie && !ie9){
1348 io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
1350 // IE will throw a security exception in an SSL environment if the
1351 // iframe source is undefined.
1352 if(typeof secureUri == 'boolean'){
1353 io.src = 'javascript:false';
1357 io = document.createElement('iframe');
1362 io.style.position = 'absolute';
1363 io.style.top = '-1000px';
1364 io.style.left = '-1000px';
1366 document.body.appendChild(io);
1370 * @description Parses the POST data and creates hidden form elements
1371 * for each key-value, and appends them to the HTML form object.
1372 * @method appendPostData
1375 * @param {string} postData The HTTP POST data
1376 * @return {array} formElements Collection of hidden fields.
1378 function _appendPostData(postData){
1379 var formElements = [],
1380 postMessage = postData.split('&'),
1383 for(i=0; i < postMessage.length; i++){
1384 delimitPos = postMessage[i].indexOf('=');
1385 if(delimitPos != -1){
1386 formElements[i] = document.createElement('input');
1387 formElements[i].type = 'hidden';
1388 formElements[i].name = decodeURIComponent(postMessage[i].substring(0,delimitPos));
1389 formElements[i].value = decodeURIComponent(postMessage[i].substring(delimitPos+1));
1390 this._formNode.appendChild(formElements[i]);
1394 return formElements;
1398 * @description Uploads HTML form, inclusive of files/attachments, using the
1399 * iframe created in createFrame to facilitate the transaction.
1400 * @method uploadFile
1403 * @param {int} id The transaction id.
1404 * @param {object} callback User-defined callback object.
1405 * @param {string} uri Fully qualified path of resource.
1406 * @param {string} postData POST data to be submitted in addition to HTML form.
1409 function _uploadFile(o, callback, uri, postData){
1410 // Each iframe has an id prefix of "yuiIO" followed
1411 // by the unique transaction id.
1412 var frameId = 'yuiIO' + o.tId,
1413 uploadEncoding = 'multipart/form-data',
1414 io = document.getElementById(frameId),
1415 ie8 = (dM >= 8) ? true : false,
1417 args = (callback && callback.argument)?callback.argument:null,
1418 oElements,i,prop,obj, rawFormAttributes, uploadCallback;
1420 // Track original HTML form attribute values.
1421 rawFormAttributes = {
1422 action:this._formNode.getAttribute('action'),
1423 method:this._formNode.getAttribute('method'),
1424 target:this._formNode.getAttribute('target')
1427 // Initialize the HTML form properties in case they are
1428 // not defined in the HTML form.
1429 this._formNode.setAttribute('action', uri);
1430 this._formNode.setAttribute('method', 'POST');
1431 this._formNode.setAttribute('target', frameId);
1433 if(YAHOO.env.ua.ie && !ie8){
1434 // IE does not respect property enctype for HTML forms.
1435 // Instead it uses the property - "encoding".
1436 this._formNode.setAttribute('encoding', uploadEncoding);
1439 this._formNode.setAttribute('enctype', uploadEncoding);
1443 oElements = this.appendPostData(postData);
1446 // Start file upload.
1447 this._formNode.submit();
1449 // Fire global custom event -- startEvent
1450 this.startEvent.fire(o, args);
1453 // Fire transaction custom event -- startEvent
1454 o.startEvent.fire(o, args);
1457 // Start polling if a callback is present and the timeout
1458 // property has been defined.
1459 if(callback && callback.timeout){
1460 this._timeOut[o.tId] = window.setTimeout(function(){ oConn.abort(o, callback, true); }, callback.timeout);
1463 // Remove HTML elements created by appendPostData
1464 if(oElements && oElements.length > 0){
1465 for(i=0; i < oElements.length; i++){
1466 this._formNode.removeChild(oElements[i]);
1470 // Restore HTML form attributes to their original
1471 // values prior to file upload.
1472 for(prop in rawFormAttributes){
1473 if(YAHOO.lang.hasOwnProperty(rawFormAttributes, prop)){
1474 if(rawFormAttributes[prop]){
1475 this._formNode.setAttribute(prop, rawFormAttributes[prop]);
1478 this._formNode.removeAttribute(prop);
1483 // Reset HTML form state properties.
1484 this.resetFormState();
1486 // Create the upload callback handler that fires when the iframe
1487 // receives the load event. Subsequently, the event handler is detached
1488 // and the iframe removed from the document.
1489 uploadCallback = function() {
1490 var body, pre, text;
1492 if(callback && callback.timeout){
1493 window.clearTimeout(oConn._timeOut[o.tId]);
1494 delete oConn._timeOut[o.tId];
1497 // Fire global custom event -- completeEvent
1498 oConn.completeEvent.fire(o, args);
1500 if(o.completeEvent){
1501 // Fire transaction custom event -- completeEvent
1502 o.completeEvent.fire(o, args);
1512 body = io.contentWindow.document.getElementsByTagName('body')[0];
1513 pre = io.contentWindow.document.getElementsByTagName('pre')[0];
1517 text = pre.textContent?pre.textContent:pre.innerText;
1520 text = body.textContent?body.textContent:body.innerText;
1523 obj.responseText = text;
1524 // responseText and responseXML will be populated with the same data from the iframe.
1525 // Since the HTTP headers cannot be read from the iframe
1526 obj.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
1530 if(callback && callback.upload){
1531 if(!callback.scope){
1532 callback.upload(obj);
1535 callback.upload.apply(callback.scope, [obj]);
1539 // Fire global custom event -- uploadEvent
1540 oConn.uploadEvent.fire(obj);
1543 // Fire transaction custom event -- uploadEvent
1544 o.uploadEvent.fire(obj);
1547 YE.removeListener(io, "load", uploadCallback);
1551 document.body.removeChild(io);
1552 oConn.releaseObject(o);
1556 // Bind the onload handler to the iframe to detect the file upload response.
1557 YE.addListener(io, "load", uploadCallback);
1560 YCM.setForm = _setForm;
1561 YCM.resetFormState = _resetFormState;
1562 YCM.createFrame = _createFrame;
1563 YCM.appendPostData = _appendPostData;
1564 YCM.uploadFile = _uploadFile;
1567 YAHOO.register("connection", YAHOO.util.Connect, {version: "2.9.0", build: "2800"});