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.
984 var YCM = YAHOO.util.Connect, _fn = {};
987 * @description This method creates and instantiates the Flash transport.
991 * @param {string} URI to connection.swf.
995 var o = '<object id="YUIConnectionSwf" type="application/x-shockwave-flash" data="' +
996 uri + '" width="0" height="0">' +
997 '<param name="movie" value="' + uri + '">' +
998 '<param name="allowScriptAccess" value="always">' +
1000 c = document.createElement('div');
1002 document.body.appendChild(c);
1007 * @description This method calls the public method on the
1008 * Flash transport to start the XDR transaction. It is analogous
1009 * to Connection Manager's asyncRequest method.
1013 * @param {object} The transaction object.
1014 * @param {string} HTTP request method.
1015 * @param {string} URI for the transaction.
1016 * @param {object} The transaction's callback object.
1017 * @param {object} The JSON object used as HTTP POST data.
1020 function _xdr(o, m, u, c, d) {
1021 _fn[parseInt(o.tId)] = { 'o':o, 'c':c };
1027 o.conn.send(u, c, o.tId);
1031 * @description This method instantiates the Flash transport and
1032 * establishes a static reference to it, used for all XDR requests.
1036 * @param {string} URI to connection.swf.
1039 function _init(uri) {
1041 YCM._transport = document.getElementById('YUIConnectionSwf');
1044 function _xdrReady() {
1045 YCM.xdrReadyEvent.fire();
1049 * @description This method fires the global and transaction start
1054 * @param {object} The transaction object.
1055 * @param {string} The transaction's callback object.
1058 function _xdrStart(o, cb) {
1060 // Fire global custom event -- startEvent
1061 YCM.startEvent.fire(o, cb.argument);
1064 // Fire transaction custom event -- startEvent
1065 o.startEvent.fire(o, cb.argument);
1071 * @description This method is the initial response handler
1072 * for XDR transactions. The Flash transport calls this
1073 * function and sends the response payload.
1074 * @method handleXdrResponse
1077 * @param {object} The response object sent from the Flash transport.
1080 function _handleXdrResponse(r) {
1081 var o = _fn[r.tId].o,
1084 if (r.statusText === 'xdr:start') {
1089 r.responseText = decodeURI(r.responseText);
1092 o.r.argument = cb.argument;
1095 this.handleTransactionResponse(o, cb, r.statusText === 'xdr:abort' ? true : false);
1099 // Bind the functions to Connection Manager as static fields.
1102 YCM.transport = _init;
1103 YCM.xdrReadyEvent = new YAHOO.util.CustomEvent('xdrReady');
1104 YCM.xdrReady = _xdrReady;
1105 YCM.handleXdrResponse = _handleXdrResponse;
1112 var YCM = YAHOO.util.Connect,
1113 YE = YAHOO.util.Event;
1115 * @description Property modified by setForm() to determine if the data
1116 * should be submitted as an HTML form.
1117 * @property _isFormSubmit
1122 YCM._isFormSubmit = false;
1125 * @description Property modified by setForm() to determine if a file(s)
1126 * upload is expected.
1127 * @property _isFileUpload
1132 YCM._isFileUpload = false;
1135 * @description Property modified by setForm() to set a reference to the HTML
1136 * form node if the desired action is file upload.
1137 * @property _formNode
1142 YCM._formNode = null;
1145 * @description Property modified by setForm() to set the HTML form data
1146 * for each transaction.
1147 * @property _sFormData
1152 YCM._sFormData = null;
1155 * @description Tracks the name-value pair of the "clicked" submit button if multiple submit
1156 * buttons are present in an HTML form; and, if YAHOO.util.Event is available.
1157 * @property _submitElementValue
1162 YCM._submitElementValue = null;
1165 * @description Custom event that fires when handleTransactionResponse() determines a
1166 * response in the HTTP 4xx/5xx range.
1167 * @property failureEvent
1172 YCM.uploadEvent = new YAHOO.util.CustomEvent('upload'),
1175 * @description Determines whether YAHOO.util.Event is available and returns true or false.
1176 * If true, an event listener is bound at the document level to trap click events that
1177 * resolve to a target type of "Submit". This listener will enable setForm() to determine
1178 * the clicked "Submit" value in a multi-Submit button, HTML form.
1179 * @property _hasSubmitListener
1183 YCM._hasSubmitListener = function() {
1189 var obj = YE.getTarget(e),
1190 name = obj.nodeName.toLowerCase();
1192 if((name === 'input' || name === 'button') && (obj.type && obj.type.toLowerCase() == 'submit')){
1193 YCM._submitElementValue = encodeURIComponent(obj.name) + "=" + encodeURIComponent(obj.value);
1202 * @description This method assembles the form label and value pairs and
1203 * constructs an encoded string.
1204 * asyncRequest() will automatically initialize the transaction with a
1205 * a HTTP header Content-Type of application/x-www-form-urlencoded.
1209 * @param {string || object} form id or name attribute, or form object.
1210 * @param {boolean} optional enable file upload.
1211 * @param {boolean} optional enable file upload over SSL in IE only.
1212 * @return {string} string of the HTML form field name and value pairs..
1214 function _setForm(formId, isUpload, secureUri)
1216 var oForm, oElement, oName, oValue, oDisabled,
1218 data = [], item = 0,
1221 this.resetFormState();
1223 if(typeof formId == 'string'){
1224 // Determine if the argument is a form id or a form name.
1225 // Note form name usage is deprecated by supported
1226 // here for legacy reasons.
1227 oForm = (document.getElementById(formId) || document.forms[formId]);
1229 else if(typeof formId == 'object'){
1230 // Treat argument as an HTML form object.
1234 YAHOO.log('Unable to create form object ' + formId, 'warn', 'Connection');
1238 // If the isUpload argument is true, setForm will call createFrame to initialize
1239 // an iframe as the form target.
1241 // The argument secureURI is also required by IE in SSL environments
1242 // where the secureURI string is a fully qualified HTTP path, used to set the source
1243 // of the iframe, to a stub resource in the same domain.
1246 // Create iframe in preparation for file upload.
1247 this.createFrame(secureUri?secureUri:null);
1249 // Set form reference and file upload properties to true.
1250 this._isFormSubmit = true;
1251 this._isFileUpload = true;
1252 this._formNode = oForm;
1257 // Iterate over the form elements collection to construct the
1258 // label-value pairs.
1259 for (i=0,len=oForm.elements.length; i<len; ++i){
1260 oElement = oForm.elements[i];
1261 oDisabled = oElement.disabled;
1262 oName = oElement.name;
1264 // Do not submit fields that are disabled or
1265 // do not have a name attribute value.
1266 if(!oDisabled && oName)
1268 oName = encodeURIComponent(oName)+'=';
1269 oValue = encodeURIComponent(oElement.value);
1271 switch(oElement.type)
1273 // Safari, Opera, FF all default opt.value from .text if
1274 // value attribute not specified in markup
1276 if (oElement.selectedIndex > -1) {
1277 opt = oElement.options[oElement.selectedIndex];
1278 data[item++] = oName + encodeURIComponent(
1279 (opt.attributes.value && opt.attributes.value.specified) ? opt.value : opt.text);
1282 case 'select-multiple':
1283 if (oElement.selectedIndex > -1) {
1284 for(j=oElement.selectedIndex, jlen=oElement.options.length; j<jlen; ++j){
1285 opt = oElement.options[j];
1287 data[item++] = oName + encodeURIComponent(
1288 (opt.attributes.value && opt.attributes.value.specified) ? opt.value : opt.text);
1295 if(oElement.checked){
1296 data[item++] = oName + oValue;
1300 // stub case as XMLHttpRequest will only send the file path as a string.
1302 // stub case for fieldset element which returns undefined.
1304 // stub case for input type reset button.
1306 // stub case for input type button elements.
1309 if(hasSubmit === false){
1310 if(this._hasSubmitListener && this._submitElementValue){
1311 data[item++] = this._submitElementValue;
1317 data[item++] = oName + oValue;
1322 this._isFormSubmit = true;
1323 this._sFormData = data.join('&');
1325 YAHOO.log('Form initialized for transaction. HTML form POST message is: ' + this._sFormData, 'info', 'Connection');
1327 this.initHeader('Content-Type', this._default_form_header);
1328 YAHOO.log('Initialize header Content-Type to application/x-www-form-urlencoded for setForm() transaction.', 'info', 'Connection');
1330 return this._sFormData;
1334 * @description Resets HTML form properties when an HTML form or HTML form
1335 * with file upload transaction is sent.
1336 * @method resetFormState
1341 function _resetFormState(){
1342 this._isFormSubmit = false;
1343 this._isFileUpload = false;
1344 this._formNode = null;
1345 this._sFormData = "";
1350 * @description Creates an iframe to be used for form file uploads. It is remove from the
1351 * document upon completion of the upload transaction.
1352 * @method createFrame
1355 * @param {string} optional qualified path of iframe resource for SSL in IE.
1358 function _createFrame(secureUri){
1360 // IE does not allow the setting of id and name attributes as object
1361 // properties via createElement(). A different iframe creation
1362 // pattern is required for IE.
1363 var frameId = 'yuiIO' + this._transaction_id,
1365 if(YAHOO.env.ua.ie){
1366 io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
1368 // IE will throw a security exception in an SSL environment if the
1369 // iframe source is undefined.
1370 if(typeof secureUri == 'boolean'){
1371 io.src = 'javascript:false';
1375 io = document.createElement('iframe');
1380 io.style.position = 'absolute';
1381 io.style.top = '-1000px';
1382 io.style.left = '-1000px';
1384 document.body.appendChild(io);
1385 YAHOO.log('File upload iframe created. Id is:' + frameId, 'info', 'Connection');
1389 * @description Parses the POST data and creates hidden form elements
1390 * for each key-value, and appends them to the HTML form object.
1391 * @method appendPostData
1394 * @param {string} postData The HTTP POST data
1395 * @return {array} formElements Collection of hidden fields.
1397 function _appendPostData(postData){
1398 var formElements = [],
1399 postMessage = postData.split('&'),
1402 for(i=0; i < postMessage.length; i++){
1403 delimitPos = postMessage[i].indexOf('=');
1404 if(delimitPos != -1){
1405 formElements[i] = document.createElement('input');
1406 formElements[i].type = 'hidden';
1407 formElements[i].name = decodeURIComponent(postMessage[i].substring(0,delimitPos));
1408 formElements[i].value = decodeURIComponent(postMessage[i].substring(delimitPos+1));
1409 this._formNode.appendChild(formElements[i]);
1413 return formElements;
1417 * @description Uploads HTML form, inclusive of files/attachments, using the
1418 * iframe created in createFrame to facilitate the transaction.
1419 * @method uploadFile
1422 * @param {int} id The transaction id.
1423 * @param {object} callback User-defined callback object.
1424 * @param {string} uri Fully qualified path of resource.
1425 * @param {string} postData POST data to be submitted in addition to HTML form.
1428 function _uploadFile(o, callback, uri, postData){
1429 // Each iframe has an id prefix of "yuiIO" followed
1430 // by the unique transaction id.
1431 var frameId = 'yuiIO' + o.tId,
1432 uploadEncoding = 'multipart/form-data',
1433 io = document.getElementById(frameId),
1434 ie8 = (document.documentMode && document.documentMode === 8) ? true : false,
1436 args = (callback && callback.argument)?callback.argument:null,
1437 oElements,i,prop,obj, rawFormAttributes, uploadCallback;
1439 // Track original HTML form attribute values.
1440 rawFormAttributes = {
1441 action:this._formNode.getAttribute('action'),
1442 method:this._formNode.getAttribute('method'),
1443 target:this._formNode.getAttribute('target')
1446 // Initialize the HTML form properties in case they are
1447 // not defined in the HTML form.
1448 this._formNode.setAttribute('action', uri);
1449 this._formNode.setAttribute('method', 'POST');
1450 this._formNode.setAttribute('target', frameId);
1452 if(YAHOO.env.ua.ie && !ie8){
1453 // IE does not respect property enctype for HTML forms.
1454 // Instead it uses the property - "encoding".
1455 this._formNode.setAttribute('encoding', uploadEncoding);
1458 this._formNode.setAttribute('enctype', uploadEncoding);
1462 oElements = this.appendPostData(postData);
1465 // Start file upload.
1466 this._formNode.submit();
1468 // Fire global custom event -- startEvent
1469 this.startEvent.fire(o, args);
1472 // Fire transaction custom event -- startEvent
1473 o.startEvent.fire(o, args);
1476 // Start polling if a callback is present and the timeout
1477 // property has been defined.
1478 if(callback && callback.timeout){
1479 this._timeOut[o.tId] = window.setTimeout(function(){ oConn.abort(o, callback, true); }, callback.timeout);
1482 // Remove HTML elements created by appendPostData
1483 if(oElements && oElements.length > 0){
1484 for(i=0; i < oElements.length; i++){
1485 this._formNode.removeChild(oElements[i]);
1489 // Restore HTML form attributes to their original
1490 // values prior to file upload.
1491 for(prop in rawFormAttributes){
1492 if(YAHOO.lang.hasOwnProperty(rawFormAttributes, prop)){
1493 if(rawFormAttributes[prop]){
1494 this._formNode.setAttribute(prop, rawFormAttributes[prop]);
1497 this._formNode.removeAttribute(prop);
1502 // Reset HTML form state properties.
1503 this.resetFormState();
1505 // Create the upload callback handler that fires when the iframe
1506 // receives the load event. Subsequently, the event handler is detached
1507 // and the iframe removed from the document.
1508 uploadCallback = function() {
1509 if(callback && callback.timeout){
1510 window.clearTimeout(oConn._timeOut[o.tId]);
1511 delete oConn._timeOut[o.tId];
1514 // Fire global custom event -- completeEvent
1515 oConn.completeEvent.fire(o, args);
1517 if(o.completeEvent){
1518 // Fire transaction custom event -- completeEvent
1519 o.completeEvent.fire(o, args);
1524 argument : callback.argument
1529 // responseText and responseXML will be populated with the same data from the iframe.
1530 // Since the HTTP headers cannot be read from the iframe
1531 obj.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:io.contentWindow.document.documentElement.textContent;
1532 obj.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
1536 if(callback && callback.upload){
1537 if(!callback.scope){
1538 callback.upload(obj);
1539 YAHOO.log('Upload callback.', 'info', 'Connection');
1542 callback.upload.apply(callback.scope, [obj]);
1543 YAHOO.log('Upload callback with scope.', 'info', 'Connection');
1547 // Fire global custom event -- uploadEvent
1548 oConn.uploadEvent.fire(obj);
1551 // Fire transaction custom event -- uploadEvent
1552 o.uploadEvent.fire(obj);
1555 YE.removeListener(io, "load", uploadCallback);
1559 document.body.removeChild(io);
1560 oConn.releaseObject(o);
1561 YAHOO.log('File upload iframe destroyed. Id is:' + frameId, 'info', 'Connection');
1565 // Bind the onload handler to the iframe to detect the file upload response.
1566 YE.addListener(io, "load", uploadCallback);
1569 YCM.setForm = _setForm;
1570 YCM.resetFormState = _resetFormState;
1571 YCM.createFrame = _createFrame;
1572 YCM.appendPostData = _appendPostData;
1573 YCM.uploadFile = _uploadFile;
1576 YAHOO.register("connection", YAHOO.util.Connect, {version: "2.8.0r4", build: "2449"});