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);
252 * @description Member to override the default POST header.
253 * @method setDefaultPostHeader
256 * @param {boolean} b Set and use default header - true or false .
259 setDefaultPostHeader:function(b)
261 if(typeof b == 'string'){
262 this._default_post_header = b;
264 else if(typeof b == 'boolean'){
265 this._use_default_post_header = b;
270 * @description Member to override the default transaction header..
271 * @method setDefaultXhrHeader
274 * @param {boolean} b Set and use default header - true or false .
277 setDefaultXhrHeader:function(b)
279 if(typeof b == 'string'){
280 this._default_xhr_header = b;
283 this._use_default_xhr_header = b;
288 * @description Member to modify the default polling interval.
289 * @method setPollingInterval
292 * @param {int} i The polling interval in milliseconds.
295 setPollingInterval:function(i)
297 if(typeof i == 'number' && isFinite(i)){
298 this._polling_interval = i;
303 * @description Instantiates a XMLHttpRequest object and returns an object with two properties:
304 * the XMLHttpRequest instance and the transaction id.
305 * @method createXhrObject
308 * @param {int} transactionId Property containing the transaction id for this transaction.
311 createXhrObject:function(transactionId)
316 // Instantiates XMLHttpRequest in non-IE browsers and assigns to http.
317 http = new XMLHttpRequest();
318 // Object literal with http and tId properties
319 obj = { conn:http, tId:transactionId, xhr: true };
323 for(i=0; i<this._msxml_progid.length; ++i){
326 // Instantiates XMLHttpRequest for IE and assign to http
327 http = new ActiveXObject(this._msxml_progid[i]);
328 // Object literal with conn and tId properties
329 obj = { conn:http, tId:transactionId, xhr: true };
342 * @description This method is called by asyncRequest to create a
343 * valid connection object for the transaction. It also passes a
344 * transaction id and increments the transaction id counter.
345 * @method getConnectionObject
350 getConnectionObject:function(t)
352 var o, tId = this._transaction_id;
357 o = this.createXhrObject(tId);
362 o.conn = this._transport;
365 else if(t==='upload'){
371 this._transaction_id++;
379 * @description Method for initiating an asynchronous request via the XHR object.
380 * @method asyncRequest
383 * @param {string} method HTTP transaction method
384 * @param {string} uri Fully qualified path of resource
385 * @param {callback} callback User-defined callback function or object
386 * @param {string} postData POST body
387 * @return {object} Returns the connection object
389 asyncRequest:function(method, uri, callback, postData)
391 var o,t,args = (callback && callback.argument)?callback.argument:null;
393 if(this._isFileUpload){
396 else if(callback.xdr){
400 o = this.getConnectionObject(t);
406 // Intialize any transaction-specific custom events, if provided.
407 if(callback && callback.customevents){
408 this.initCustomEvents(o, callback);
411 if(this._isFormSubmit){
412 if(this._isFileUpload){
413 this.uploadFile(o, callback, uri, postData);
417 // If the specified HTTP method is GET, setForm() will return an
418 // encoded string that is concatenated to the uri to
419 // create a querystring.
420 if(method.toUpperCase() == 'GET'){
421 if(this._sFormData.length !== 0){
422 // If the URI already contains a querystring, append an ampersand
423 // and then concatenate _sFormData to the URI.
424 uri += ((uri.indexOf('?') == -1)?'?':'&') + this._sFormData;
427 else if(method.toUpperCase() == 'POST'){
428 // If POST data exist in addition to the HTML form data,
429 // it will be concatenated to the form data.
430 postData = postData?this._sFormData + "&" + postData:this._sFormData;
434 if(method.toUpperCase() == 'GET' && (callback && callback.cache === false)){
435 // If callback.cache is defined and set to false, a
436 // timestamp value will be added to the querystring.
437 uri += ((uri.indexOf('?') == -1)?'?':'&') + "rnd=" + new Date().valueOf().toString();
440 // Each transaction will automatically include a custom header of
441 // "X-Requested-With: XMLHttpRequest" to identify the request as
442 // having originated from Connection Manager.
443 if(this._use_default_xhr_header){
444 if(!this._default_headers['X-Requested-With']){
445 this.initHeader('X-Requested-With', this._default_xhr_header, true);
449 //If the transaction method is POST and the POST header value is set to true
450 //or a custom value, initalize the Content-Type header to this value.
451 if((method.toUpperCase() === 'POST' && this._use_default_post_header) && this._isFormSubmit === false){
452 this.initHeader('Content-Type', this._default_post_header);
456 this.xdr(o, method, uri, callback, postData);
460 o.conn.open(method, uri, true);
461 //Initialize all default and custom HTTP headers,
462 if(this._has_default_headers || this._has_http_headers){
466 this.handleReadyState(o, callback);
467 o.conn.send(postData || '');
469 // Reset the HTML form data and state properties as
470 // soon as the data are submitted.
471 if(this._isFormSubmit === true){
472 this.resetFormState();
475 // Fire global custom event -- startEvent
476 this.startEvent.fire(o, args);
479 // Fire transaction custom event -- startEvent
480 o.startEvent.fire(o, args);
488 * @description This method creates and subscribes custom events,
489 * specific to each transaction
490 * @method initCustomEvents
493 * @param {object} o The connection object
494 * @param {callback} callback The user-defined callback object
497 initCustomEvents:function(o, callback)
500 // Enumerate through callback.customevents members and bind/subscribe
501 // events that match in the _customEvents table.
502 for(prop in callback.customevents){
503 if(this._customEvents[prop][0]){
504 // Create the custom event
505 o[this._customEvents[prop][0]] = new YAHOO.util.CustomEvent(this._customEvents[prop][1], (callback.scope)?callback.scope:null);
507 // Subscribe the custom event
508 o[this._customEvents[prop][0]].subscribe(callback.customevents[prop]);
514 * @description This method serves as a timer that polls the XHR object's readyState
515 * property during a transaction, instead of binding a callback to the
516 * onreadystatechange event. Upon readyState 4, handleTransactionResponse
517 * will process the response, and the timer will be cleared.
518 * @method handleReadyState
521 * @param {object} o The connection object
522 * @param {callback} callback The user-defined callback object
526 handleReadyState:function(o, callback)
530 args = (callback && callback.argument)?callback.argument:null;
532 if(callback && callback.timeout){
533 this._timeOut[o.tId] = window.setTimeout(function(){ oConn.abort(o, callback, true); }, callback.timeout);
536 this._poll[o.tId] = window.setInterval(
538 if(o.conn && o.conn.readyState === 4){
540 // Clear the polling interval for the transaction
541 // and remove the reference from _poll.
542 window.clearInterval(oConn._poll[o.tId]);
543 delete oConn._poll[o.tId];
545 if(callback && callback.timeout){
546 window.clearTimeout(oConn._timeOut[o.tId]);
547 delete oConn._timeOut[o.tId];
550 // Fire global custom event -- completeEvent
551 oConn.completeEvent.fire(o, args);
554 // Fire transaction custom event -- completeEvent
555 o.completeEvent.fire(o, args);
558 oConn.handleTransactionResponse(o, callback);
561 ,this._polling_interval);
565 * @description This method attempts to interpret the server response and
566 * determine whether the transaction was successful, or if an error or
567 * exception was encountered.
568 * @method handleTransactionResponse
571 * @param {object} o The connection object
572 * @param {object} callback The user-defined callback object
573 * @param {boolean} isAbort Determines if the transaction was terminated via abort().
576 handleTransactionResponse:function(o, callback, isAbort)
578 var httpStatus, responseObject,
579 args = (callback && callback.argument)?callback.argument:null,
580 xdrS = (o.r && o.r.statusText === 'xdr:success')?true:false,
581 xdrF = (o.r && o.r.statusText === 'xdr:failure')?true:false,
586 if((o.conn.status !== undefined && o.conn.status !== 0) || xdrS){
587 // XDR requests will not have HTTP status defined. The
588 // statusText property will define the response status
589 // set by the Flash transport.
590 httpStatus = o.conn.status;
592 else if(xdrF && !xdrA){
593 // Set XDR transaction failure to a status of 0, which
594 // resolves as an HTTP failure, instead of an exception.
603 // 13030 is a custom code to indicate the condition -- in Mozilla/FF --
604 // when the XHR object's status and statusText properties are
605 // unavailable, and a query attempt throws an exception.
609 if((httpStatus >= 200 && httpStatus < 300) || httpStatus === 1223 || xdrS){
610 responseObject = o.xdr ? o.r : this.createResponseObject(o, args);
611 if(callback && callback.success){
613 callback.success(responseObject);
616 // If a scope property is defined, the callback will be fired from
617 // the context of the object.
618 callback.success.apply(callback.scope, [responseObject]);
622 // Fire global custom event -- successEvent
623 this.successEvent.fire(responseObject);
626 // Fire transaction custom event -- successEvent
627 o.successEvent.fire(responseObject);
632 // The following cases are wininet.dll error codes that may be encountered.
633 case 12002: // Server timeout
634 case 12029: // 12029 to 12031 correspond to dropped connections.
637 case 12152: // Connection closed by server.
638 case 13030: // See above comments for variable status.
639 // XDR transactions will not resolve to this case, since the
640 // response object is already built in the xdr response.
641 responseObject = this.createExceptionObject(o.tId, args, (isAbort?isAbort:false));
642 if(callback && callback.failure){
644 callback.failure(responseObject);
647 callback.failure.apply(callback.scope, [responseObject]);
653 responseObject = (o.xdr) ? o.response : this.createResponseObject(o, args);
654 if(callback && callback.failure){
656 callback.failure(responseObject);
659 callback.failure.apply(callback.scope, [responseObject]);
664 // Fire global custom event -- failureEvent
665 this.failureEvent.fire(responseObject);
668 // Fire transaction custom event -- failureEvent
669 o.failureEvent.fire(responseObject);
674 this.releaseObject(o);
675 responseObject = null;
679 * @description This method evaluates the server response, creates and returns the results via
680 * its properties. Success and failure cases will differ in the response
681 * object's property values.
682 * @method createResponseObject
685 * @param {object} o The connection object
686 * @param {callbackArg} callbackArg The user-defined argument or arguments to be passed to the callback
689 createResponseObject:function(o, callbackArg)
691 var obj = {}, headerObj = {},
692 i, headerStr, header, delimitPos;
696 headerStr = o.conn.getAllResponseHeaders();
697 header = headerStr.split('\n');
698 for(i=0; i<header.length; i++){
699 delimitPos = header[i].indexOf(':');
700 if(delimitPos != -1){
701 headerObj[header[i].substring(0,delimitPos)] = YAHOO.lang.trim(header[i].substring(delimitPos+2));
708 // Normalize IE's response to HTTP 204 when Win error 1223.
709 obj.status = (o.conn.status == 1223)?204:o.conn.status;
710 // Normalize IE's statusText to "No Content" instead of "Unknown".
711 obj.statusText = (o.conn.status == 1223)?"No Content":o.conn.statusText;
712 obj.getResponseHeader = headerObj;
713 obj.getAllResponseHeaders = headerStr;
714 obj.responseText = o.conn.responseText;
715 obj.responseXML = o.conn.responseXML;
718 obj.argument = callbackArg;
725 * @description If a transaction cannot be completed due to dropped or closed connections,
726 * there may be not be enough information to build a full response object.
727 * The failure callback will be fired and this specific condition can be identified
728 * by a status property value of 0.
730 * If an abort was successful, the status property will report a value of -1.
732 * @method createExceptionObject
735 * @param {int} tId The Transaction Id
736 * @param {callbackArg} callbackArg The user-defined argument or arguments to be passed to the callback
737 * @param {boolean} isAbort Determines if the exception case is caused by a transaction abort
740 createExceptionObject:function(tId, callbackArg, isAbort)
743 COMM_ERROR = 'communication failure',
745 ABORT_ERROR = 'transaction aborted',
750 obj.status = ABORT_CODE;
751 obj.statusText = ABORT_ERROR;
754 obj.status = COMM_CODE;
755 obj.statusText = COMM_ERROR;
759 obj.argument = callbackArg;
766 * @description Method that initializes the custom HTTP headers for the each transaction.
770 * @param {string} label The HTTP header label
771 * @param {string} value The HTTP header value
772 * @param {string} isDefault Determines if the specific header is a default header
773 * automatically sent with each transaction.
776 initHeader:function(label, value, isDefault)
778 var headerObj = (isDefault)?this._default_headers:this._http_headers;
780 headerObj[label] = value;
782 this._has_default_headers = true;
785 this._has_http_headers = true;
791 * @description Accessor that sets the HTTP headers for each transaction.
795 * @param {object} o The connection object for the transaction.
798 setHeader:function(o)
801 if(this._has_default_headers){
802 for(prop in this._default_headers){
803 if(YAHOO.lang.hasOwnProperty(this._default_headers, prop)){
804 o.conn.setRequestHeader(prop, this._default_headers[prop]);
809 if(this._has_http_headers){
810 for(prop in this._http_headers){
811 if(YAHOO.lang.hasOwnProperty(this._http_headers, prop)){
812 o.conn.setRequestHeader(prop, this._http_headers[prop]);
816 this._http_headers = {};
817 this._has_http_headers = false;
822 * @description Resets the default HTTP headers object
823 * @method resetDefaultHeaders
828 resetDefaultHeaders:function(){
829 this._default_headers = {};
830 this._has_default_headers = false;
834 * @description Method to terminate a transaction, if it has not reached readyState 4.
838 * @param {object} o The connection object returned by asyncRequest.
839 * @param {object} callback User-defined callback object.
840 * @param {string} isTimeout boolean to indicate if abort resulted from a callback timeout.
843 abort:function(o, callback, isTimeout)
846 args = (callback && callback.argument)?callback.argument:null;
851 if(this.isCallInProgress(o)){
852 // Issue abort request
855 window.clearInterval(this._poll[o.tId]);
856 delete this._poll[o.tId];
859 window.clearTimeout(this._timeOut[o.tId]);
860 delete this._timeOut[o.tId];
872 var frameId = 'yuiIO' + o.tId;
873 var io = document.getElementById(frameId);
876 // Remove all listeners on the iframe prior to
878 YAHOO.util.Event.removeListener(io, "load");
879 // Destroy the iframe facilitating the transaction.
880 document.body.removeChild(io);
883 window.clearTimeout(this._timeOut[o.tId]);
884 delete this._timeOut[o.tId];
894 if(abortStatus === true){
895 // Fire global custom event -- abortEvent
896 this.abortEvent.fire(o, args);
899 // Fire transaction custom event -- abortEvent
900 o.abortEvent.fire(o, args);
903 this.handleTransactionResponse(o, callback, true);
910 * @description Determines if the transaction is still being processed.
911 * @method isCallInProgress
914 * @param {object} o The connection object returned by asyncRequest
917 isCallInProgress:function(o)
920 // if the XHR object assigned to the transaction has not been dereferenced,
921 // then check its readyState status. Otherwise, return false.
923 return o.conn.readyState !== 4 && o.conn.readyState !== 0;
925 else if(o.xdr && o.conn){
926 return o.conn.isCallInProgress(o.tId);
928 else if(o.upload === true){
929 return document.getElementById('yuiIO' + o.tId)?true:false;
937 * @description Dereference the XHR instance and the connection object after the transaction is completed.
938 * @method releaseObject
941 * @param {object} o The connection object
944 releaseObject:function(o)
947 //dereference the XHR instance.
951 //dereference the connection object.
961 var YCM = YAHOO.util.Connect, _fn = {};
964 * @description This method creates and instantiates the Flash transport.
968 * @param {string} URI to connection.swf.
972 var o = '<object id="YUIConnectionSwf" type="application/x-shockwave-flash" data="' +
973 uri + '" width="0" height="0">' +
974 '<param name="movie" value="' + uri + '">' +
975 '<param name="allowScriptAccess" value="always">' +
977 c = document.createElement('div');
979 document.body.appendChild(c);
984 * @description This method calls the public method on the
985 * Flash transport to start the XDR transaction. It is analogous
986 * to Connection Manager's asyncRequest method.
990 * @param {object} The transaction object.
991 * @param {string} HTTP request method.
992 * @param {string} URI for the transaction.
993 * @param {object} The transaction's callback object.
994 * @param {object} The JSON object used as HTTP POST data.
997 function _xdr(o, m, u, c, d) {
998 _fn[parseInt(o.tId)] = { 'o':o, 'c':c };
1004 o.conn.send(u, c, o.tId);
1008 * @description This method instantiates the Flash transport and
1009 * establishes a static reference to it, used for all XDR requests.
1013 * @param {string} URI to connection.swf.
1016 function _init(uri) {
1018 YCM._transport = document.getElementById('YUIConnectionSwf');
1021 function _xdrReady() {
1022 YCM.xdrReadyEvent.fire();
1026 * @description This method fires the global and transaction start
1031 * @param {object} The transaction object.
1032 * @param {string} The transaction's callback object.
1035 function _xdrStart(o, cb) {
1037 // Fire global custom event -- startEvent
1038 YCM.startEvent.fire(o, cb.argument);
1041 // Fire transaction custom event -- startEvent
1042 o.startEvent.fire(o, cb.argument);
1048 * @description This method is the initial response handler
1049 * for XDR transactions. The Flash transport calls this
1050 * function and sends the response payload.
1051 * @method handleXdrResponse
1054 * @param {object} The response object sent from the Flash transport.
1057 function _handleXdrResponse(r) {
1058 var o = _fn[r.tId].o,
1061 if (r.statusText === 'xdr:start') {
1066 r.responseText = decodeURI(r.responseText);
1069 o.r.argument = cb.argument;
1072 this.handleTransactionResponse(o, cb, r.statusText === 'xdr:abort' ? true : false);
1076 // Bind the functions to Connection Manager as static fields.
1079 YCM.transport = _init;
1080 YCM.xdrReadyEvent = new YAHOO.util.CustomEvent('xdrReady');
1081 YCM.xdrReady = _xdrReady;
1082 YCM.handleXdrResponse = _handleXdrResponse;
1089 var YCM = YAHOO.util.Connect,
1090 YE = YAHOO.util.Event;
1092 * @description Property modified by setForm() to determine if the data
1093 * should be submitted as an HTML form.
1094 * @property _isFormSubmit
1099 YCM._isFormSubmit = false;
1102 * @description Property modified by setForm() to determine if a file(s)
1103 * upload is expected.
1104 * @property _isFileUpload
1109 YCM._isFileUpload = false;
1112 * @description Property modified by setForm() to set a reference to the HTML
1113 * form node if the desired action is file upload.
1114 * @property _formNode
1119 YCM._formNode = null;
1122 * @description Property modified by setForm() to set the HTML form data
1123 * for each transaction.
1124 * @property _sFormData
1129 YCM._sFormData = null;
1132 * @description Tracks the name-value pair of the "clicked" submit button if multiple submit
1133 * buttons are present in an HTML form; and, if YAHOO.util.Event is available.
1134 * @property _submitElementValue
1139 YCM._submitElementValue = null;
1142 * @description Custom event that fires when handleTransactionResponse() determines a
1143 * response in the HTTP 4xx/5xx range.
1144 * @property failureEvent
1149 YCM.uploadEvent = new YAHOO.util.CustomEvent('upload'),
1152 * @description Determines whether YAHOO.util.Event is available and returns true or false.
1153 * If true, an event listener is bound at the document level to trap click events that
1154 * resolve to a target type of "Submit". This listener will enable setForm() to determine
1155 * the clicked "Submit" value in a multi-Submit button, HTML form.
1156 * @property _hasSubmitListener
1160 YCM._hasSubmitListener = function() {
1166 var obj = YE.getTarget(e),
1167 name = obj.nodeName.toLowerCase();
1169 if((name === 'input' || name === 'button') && (obj.type && obj.type.toLowerCase() == 'submit')){
1170 YCM._submitElementValue = encodeURIComponent(obj.name) + "=" + encodeURIComponent(obj.value);
1179 * @description This method assembles the form label and value pairs and
1180 * constructs an encoded string.
1181 * asyncRequest() will automatically initialize the transaction with a
1182 * a HTTP header Content-Type of application/x-www-form-urlencoded.
1186 * @param {string || object} form id or name attribute, or form object.
1187 * @param {boolean} optional enable file upload.
1188 * @param {boolean} optional enable file upload over SSL in IE only.
1189 * @return {string} string of the HTML form field name and value pairs..
1191 function _setForm(formId, isUpload, secureUri)
1193 var oForm, oElement, oName, oValue, oDisabled,
1195 data = [], item = 0,
1198 this.resetFormState();
1200 if(typeof formId == 'string'){
1201 // Determine if the argument is a form id or a form name.
1202 // Note form name usage is deprecated by supported
1203 // here for legacy reasons.
1204 oForm = (document.getElementById(formId) || document.forms[formId]);
1206 else if(typeof formId == 'object'){
1207 // Treat argument as an HTML form object.
1214 // If the isUpload argument is true, setForm will call createFrame to initialize
1215 // an iframe as the form target.
1217 // The argument secureURI is also required by IE in SSL environments
1218 // where the secureURI string is a fully qualified HTTP path, used to set the source
1219 // of the iframe, to a stub resource in the same domain.
1222 // Create iframe in preparation for file upload.
1223 this.createFrame(secureUri?secureUri:null);
1225 // Set form reference and file upload properties to true.
1226 this._isFormSubmit = true;
1227 this._isFileUpload = true;
1228 this._formNode = oForm;
1233 // Iterate over the form elements collection to construct the
1234 // label-value pairs.
1235 for (i=0,len=oForm.elements.length; i<len; ++i){
1236 oElement = oForm.elements[i];
1237 oDisabled = oElement.disabled;
1238 oName = oElement.name;
1240 // Do not submit fields that are disabled or
1241 // do not have a name attribute value.
1242 if(!oDisabled && oName)
1244 oName = encodeURIComponent(oName)+'=';
1245 oValue = encodeURIComponent(oElement.value);
1247 switch(oElement.type)
1249 // Safari, Opera, FF all default opt.value from .text if
1250 // value attribute not specified in markup
1252 if (oElement.selectedIndex > -1) {
1253 opt = oElement.options[oElement.selectedIndex];
1254 data[item++] = oName + encodeURIComponent(
1255 (opt.attributes.value && opt.attributes.value.specified) ? opt.value : opt.text);
1258 case 'select-multiple':
1259 if (oElement.selectedIndex > -1) {
1260 for(j=oElement.selectedIndex, jlen=oElement.options.length; j<jlen; ++j){
1261 opt = oElement.options[j];
1263 data[item++] = oName + encodeURIComponent(
1264 (opt.attributes.value && opt.attributes.value.specified) ? opt.value : opt.text);
1271 if(oElement.checked){
1272 data[item++] = oName + oValue;
1276 // stub case as XMLHttpRequest will only send the file path as a string.
1278 // stub case for fieldset element which returns undefined.
1280 // stub case for input type reset button.
1282 // stub case for input type button elements.
1285 if(hasSubmit === false){
1286 if(this._hasSubmitListener && this._submitElementValue){
1287 data[item++] = this._submitElementValue;
1293 data[item++] = oName + oValue;
1298 this._isFormSubmit = true;
1299 this._sFormData = data.join('&');
1302 this.initHeader('Content-Type', this._default_form_header);
1304 return this._sFormData;
1308 * @description Resets HTML form properties when an HTML form or HTML form
1309 * with file upload transaction is sent.
1310 * @method resetFormState
1315 function _resetFormState(){
1316 this._isFormSubmit = false;
1317 this._isFileUpload = false;
1318 this._formNode = null;
1319 this._sFormData = "";
1324 * @description Creates an iframe to be used for form file uploads. It is remove from the
1325 * document upon completion of the upload transaction.
1326 * @method createFrame
1329 * @param {string} optional qualified path of iframe resource for SSL in IE.
1332 function _createFrame(secureUri){
1334 // IE does not allow the setting of id and name attributes as object
1335 // properties via createElement(). A different iframe creation
1336 // pattern is required for IE.
1337 var frameId = 'yuiIO' + this._transaction_id,
1339 if(YAHOO.env.ua.ie){
1340 io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
1342 // IE will throw a security exception in an SSL environment if the
1343 // iframe source is undefined.
1344 if(typeof secureUri == 'boolean'){
1345 io.src = 'javascript:false';
1349 io = document.createElement('iframe');
1354 io.style.position = 'absolute';
1355 io.style.top = '-1000px';
1356 io.style.left = '-1000px';
1358 document.body.appendChild(io);
1362 * @description Parses the POST data and creates hidden form elements
1363 * for each key-value, and appends them to the HTML form object.
1364 * @method appendPostData
1367 * @param {string} postData The HTTP POST data
1368 * @return {array} formElements Collection of hidden fields.
1370 function _appendPostData(postData){
1371 var formElements = [],
1372 postMessage = postData.split('&'),
1375 for(i=0; i < postMessage.length; i++){
1376 delimitPos = postMessage[i].indexOf('=');
1377 if(delimitPos != -1){
1378 formElements[i] = document.createElement('input');
1379 formElements[i].type = 'hidden';
1380 formElements[i].name = decodeURIComponent(postMessage[i].substring(0,delimitPos));
1381 formElements[i].value = decodeURIComponent(postMessage[i].substring(delimitPos+1));
1382 this._formNode.appendChild(formElements[i]);
1386 return formElements;
1390 * @description Uploads HTML form, inclusive of files/attachments, using the
1391 * iframe created in createFrame to facilitate the transaction.
1392 * @method uploadFile
1395 * @param {int} id The transaction id.
1396 * @param {object} callback User-defined callback object.
1397 * @param {string} uri Fully qualified path of resource.
1398 * @param {string} postData POST data to be submitted in addition to HTML form.
1401 function _uploadFile(o, callback, uri, postData){
1402 // Each iframe has an id prefix of "yuiIO" followed
1403 // by the unique transaction id.
1404 var frameId = 'yuiIO' + o.tId,
1405 uploadEncoding = 'multipart/form-data',
1406 io = document.getElementById(frameId),
1407 ie8 = (document.documentMode && document.documentMode === 8) ? true : false,
1409 args = (callback && callback.argument)?callback.argument:null,
1410 oElements,i,prop,obj, rawFormAttributes, uploadCallback;
1412 // Track original HTML form attribute values.
1413 rawFormAttributes = {
1414 action:this._formNode.getAttribute('action'),
1415 method:this._formNode.getAttribute('method'),
1416 target:this._formNode.getAttribute('target')
1419 // Initialize the HTML form properties in case they are
1420 // not defined in the HTML form.
1421 this._formNode.setAttribute('action', uri);
1422 this._formNode.setAttribute('method', 'POST');
1423 this._formNode.setAttribute('target', frameId);
1425 if(YAHOO.env.ua.ie && !ie8){
1426 // IE does not respect property enctype for HTML forms.
1427 // Instead it uses the property - "encoding".
1428 this._formNode.setAttribute('encoding', uploadEncoding);
1431 this._formNode.setAttribute('enctype', uploadEncoding);
1435 oElements = this.appendPostData(postData);
1438 // Start file upload.
1439 this._formNode.submit();
1441 // Fire global custom event -- startEvent
1442 this.startEvent.fire(o, args);
1445 // Fire transaction custom event -- startEvent
1446 o.startEvent.fire(o, args);
1449 // Start polling if a callback is present and the timeout
1450 // property has been defined.
1451 if(callback && callback.timeout){
1452 this._timeOut[o.tId] = window.setTimeout(function(){ oConn.abort(o, callback, true); }, callback.timeout);
1455 // Remove HTML elements created by appendPostData
1456 if(oElements && oElements.length > 0){
1457 for(i=0; i < oElements.length; i++){
1458 this._formNode.removeChild(oElements[i]);
1462 // Restore HTML form attributes to their original
1463 // values prior to file upload.
1464 for(prop in rawFormAttributes){
1465 if(YAHOO.lang.hasOwnProperty(rawFormAttributes, prop)){
1466 if(rawFormAttributes[prop]){
1467 this._formNode.setAttribute(prop, rawFormAttributes[prop]);
1470 this._formNode.removeAttribute(prop);
1475 // Reset HTML form state properties.
1476 this.resetFormState();
1478 // Create the upload callback handler that fires when the iframe
1479 // receives the load event. Subsequently, the event handler is detached
1480 // and the iframe removed from the document.
1481 uploadCallback = function() {
1482 if(callback && callback.timeout){
1483 window.clearTimeout(oConn._timeOut[o.tId]);
1484 delete oConn._timeOut[o.tId];
1487 // Fire global custom event -- completeEvent
1488 oConn.completeEvent.fire(o, args);
1490 if(o.completeEvent){
1491 // Fire transaction custom event -- completeEvent
1492 o.completeEvent.fire(o, args);
1497 argument : callback.argument
1502 // responseText and responseXML will be populated with the same data from the iframe.
1503 // Since the HTTP headers cannot be read from the iframe
1504 obj.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:io.contentWindow.document.documentElement.textContent;
1505 obj.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
1509 if(callback && callback.upload){
1510 if(!callback.scope){
1511 callback.upload(obj);
1514 callback.upload.apply(callback.scope, [obj]);
1518 // Fire global custom event -- uploadEvent
1519 oConn.uploadEvent.fire(obj);
1522 // Fire transaction custom event -- uploadEvent
1523 o.uploadEvent.fire(obj);
1526 YE.removeListener(io, "load", uploadCallback);
1530 document.body.removeChild(io);
1531 oConn.releaseObject(o);
1535 // Bind the onload handler to the iframe to detect the file upload response.
1536 YE.addListener(io, "load", uploadCallback);
1539 YCM.setForm = _setForm;
1540 YCM.resetFormState = _resetFormState;
1541 YCM.createFrame = _createFrame;
1542 YCM.appendPostData = _appendPostData;
1543 YCM.uploadFile = _uploadFile;
1546 YAHOO.register("connection", YAHOO.util.Connect, {version: "2.8.0r4", build: "2449"});