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 Property modified by setForm() to determine if the data
135 * should be submitted as an HTML form.
136 * @property _isFormSubmit
144 * @description Property modified by setForm() to determine if a file(s)
145 * upload is expected.
146 * @property _isFileUpload
154 * @description Property modified by setForm() to set a reference to the HTML
155 * form node if the desired action is file upload.
156 * @property _formNode
164 * @description Property modified by setForm() to set the HTML form data
165 * for each transaction.
166 * @property _sFormData
174 * @description Collection of polling references to the polling mechanism in handleReadyState.
183 * @description Queue of timeout values for each transaction callback with a defined timeout value.
192 * @description The polling frequency, in milliseconds, for HandleReadyState.
193 * when attempting to determine a transaction's XHR readyState.
194 * The default is 50 milliseconds.
195 * @property _polling_interval
200 _polling_interval:50,
203 * @description A transaction counter that increments the transaction id for each transaction.
204 * @property _transaction_id
212 * @description Tracks the name-value pair of the "clicked" submit button if multiple submit
213 * buttons are present in an HTML form; and, if YAHOO.util.Event is available.
214 * @property _submitElementValue
219 _submitElementValue:null,
222 * @description Determines whether YAHOO.util.Event is available and returns true or false.
223 * If true, an event listener is bound at the document level to trap click events that
224 * resolve to a target type of "Submit". This listener will enable setForm() to determine
225 * the clicked "Submit" value in a multi-Submit button, HTML form.
226 * @property _hasSubmitListener
230 _hasSubmitListener:(function()
232 if(YAHOO.util.Event){
233 YAHOO.util.Event.addListener(
237 var obj = YAHOO.util.Event.getTarget(e),
238 name = obj.nodeName.toLowerCase();
239 if((name === 'input' || name === 'button') && (obj.type && obj.type.toLowerCase() == 'submit')){
240 YAHOO.util.Connect._submitElementValue = encodeURIComponent(obj.name) + "=" + encodeURIComponent(obj.value);
249 * @description Custom event that fires at the start of a transaction
250 * @property startEvent
255 startEvent: new YAHOO.util.CustomEvent('start'),
258 * @description Custom event that fires when a transaction response has completed.
259 * @property completeEvent
264 completeEvent: new YAHOO.util.CustomEvent('complete'),
267 * @description Custom event that fires when handleTransactionResponse() determines a
268 * response in the HTTP 2xx range.
269 * @property successEvent
274 successEvent: new YAHOO.util.CustomEvent('success'),
277 * @description Custom event that fires when handleTransactionResponse() determines a
278 * response in the HTTP 4xx/5xx range.
279 * @property failureEvent
284 failureEvent: new YAHOO.util.CustomEvent('failure'),
287 * @description Custom event that fires when handleTransactionResponse() determines a
288 * response in the HTTP 4xx/5xx range.
289 * @property failureEvent
294 uploadEvent: new YAHOO.util.CustomEvent('upload'),
297 * @description Custom event that fires when a transaction is successfully aborted.
298 * @property abortEvent
303 abortEvent: new YAHOO.util.CustomEvent('abort'),
306 * @description A reference table that maps callback custom events members to its specific
308 * @property _customEvents
315 onStart:['startEvent', 'start'],
316 onComplete:['completeEvent', 'complete'],
317 onSuccess:['successEvent', 'success'],
318 onFailure:['failureEvent', 'failure'],
319 onUpload:['uploadEvent', 'upload'],
320 onAbort:['abortEvent', 'abort']
324 * @description Member to add an ActiveX id to the existing xml_progid array.
325 * In the event(unlikely) a new ActiveX id is introduced, it can be added
326 * without internal code modifications.
330 * @param {string} id The ActiveX id to be added to initialize the XHR object.
333 setProgId:function(id)
335 this._msxml_progid.unshift(id);
339 * @description Member to override the default POST header.
340 * @method setDefaultPostHeader
343 * @param {boolean} b Set and use default header - true or false .
346 setDefaultPostHeader:function(b)
348 if(typeof b == 'string'){
349 this._default_post_header = b;
351 else if(typeof b == 'boolean'){
352 this._use_default_post_header = b;
357 * @description Member to override the default transaction header..
358 * @method setDefaultXhrHeader
361 * @param {boolean} b Set and use default header - true or false .
364 setDefaultXhrHeader:function(b)
366 if(typeof b == 'string'){
367 this._default_xhr_header = b;
370 this._use_default_xhr_header = b;
375 * @description Member to modify the default polling interval.
376 * @method setPollingInterval
379 * @param {int} i The polling interval in milliseconds.
382 setPollingInterval:function(i)
384 if(typeof i == 'number' && isFinite(i)){
385 this._polling_interval = i;
390 * @description Instantiates a XMLHttpRequest object and returns an object with two properties:
391 * the XMLHttpRequest instance and the transaction id.
392 * @method createXhrObject
395 * @param {int} transactionId Property containing the transaction id for this transaction.
398 createXhrObject:function(transactionId)
403 // Instantiates XMLHttpRequest in non-IE browsers and assigns to http.
404 http = new XMLHttpRequest();
405 // Object literal with http and tId properties
406 obj = { conn:http, tId:transactionId };
410 for(var i=0; i<this._msxml_progid.length; ++i){
413 // Instantiates XMLHttpRequest for IE and assign to http
414 http = new ActiveXObject(this._msxml_progid[i]);
415 // Object literal with conn and tId properties
416 obj = { conn:http, tId:transactionId };
429 * @description This method is called by asyncRequest to create a
430 * valid connection object for the transaction. It also passes a
431 * transaction id and increments the transaction id counter.
432 * @method getConnectionObject
437 getConnectionObject:function(isFileUpload)
440 var tId = this._transaction_id;
445 o = this.createXhrObject(tId);
454 this._transaction_id++;
465 * @description Method for initiating an asynchronous request via the XHR object.
466 * @method asyncRequest
469 * @param {string} method HTTP transaction method
470 * @param {string} uri Fully qualified path of resource
471 * @param {callback} callback User-defined callback function or object
472 * @param {string} postData POST body
473 * @return {object} Returns the connection object
475 asyncRequest:function(method, uri, callback, postData)
477 var o = (this._isFileUpload)?this.getConnectionObject(true):this.getConnectionObject();
478 var args = (callback && callback.argument)?callback.argument:null;
485 // Intialize any transaction-specific custom events, if provided.
486 if(callback && callback.customevents){
487 this.initCustomEvents(o, callback);
490 if(this._isFormSubmit){
491 if(this._isFileUpload){
492 this.uploadFile(o, callback, uri, postData);
496 // If the specified HTTP method is GET, setForm() will return an
497 // encoded string that is concatenated to the uri to
498 // create a querystring.
499 if(method.toUpperCase() == 'GET'){
500 if(this._sFormData.length !== 0){
501 // If the URI already contains a querystring, append an ampersand
502 // and then concatenate _sFormData to the URI.
503 uri += ((uri.indexOf('?') == -1)?'?':'&') + this._sFormData;
506 else if(method.toUpperCase() == 'POST'){
507 // If POST data exist in addition to the HTML form data,
508 // it will be concatenated to the form data.
509 postData = postData?this._sFormData + "&" + postData:this._sFormData;
513 if(method.toUpperCase() == 'GET' && (callback && callback.cache === false)){
514 // If callback.cache is defined and set to false, a
515 // timestamp value will be added to the querystring.
516 uri += ((uri.indexOf('?') == -1)?'?':'&') + "rnd=" + new Date().valueOf().toString();
519 o.conn.open(method, uri, true);
521 // Each transaction will automatically include a custom header of
522 // "X-Requested-With: XMLHttpRequest" to identify the request as
523 // having originated from Connection Manager.
524 if(this._use_default_xhr_header){
525 if(!this._default_headers['X-Requested-With']){
526 this.initHeader('X-Requested-With', this._default_xhr_header, true);
530 //If the transaction method is POST and the POST header value is set to true
531 //or a custom value, initalize the Content-Type header to this value.
532 if((method.toUpperCase() === 'POST' && this._use_default_post_header) && this._isFormSubmit === false){
533 this.initHeader('Content-Type', this._default_post_header);
536 //Initialize all default and custom HTTP headers,
537 if(this._has_default_headers || this._has_http_headers){
541 this.handleReadyState(o, callback);
542 o.conn.send(postData || '');
545 // Reset the HTML form data and state properties as
546 // soon as the data are submitted.
547 if(this._isFormSubmit === true){
548 this.resetFormState();
551 // Fire global custom event -- startEvent
552 this.startEvent.fire(o, args);
555 // Fire transaction custom event -- startEvent
556 o.startEvent.fire(o, args);
564 * @description This method creates and subscribes custom events,
565 * specific to each transaction
566 * @method initCustomEvents
569 * @param {object} o The connection object
570 * @param {callback} callback The user-defined callback object
573 initCustomEvents:function(o, callback)
576 // Enumerate through callback.customevents members and bind/subscribe
577 // events that match in the _customEvents table.
578 for(prop in callback.customevents){
579 if(this._customEvents[prop][0]){
580 // Create the custom event
581 o[this._customEvents[prop][0]] = new YAHOO.util.CustomEvent(this._customEvents[prop][1], (callback.scope)?callback.scope:null);
583 // Subscribe the custom event
584 o[this._customEvents[prop][0]].subscribe(callback.customevents[prop]);
590 * @description This method serves as a timer that polls the XHR object's readyState
591 * property during a transaction, instead of binding a callback to the
592 * onreadystatechange event. Upon readyState 4, handleTransactionResponse
593 * will process the response, and the timer will be cleared.
594 * @method handleReadyState
597 * @param {object} o The connection object
598 * @param {callback} callback The user-defined callback object
602 handleReadyState:function(o, callback)
606 var args = (callback && callback.argument)?callback.argument:null;
608 if(callback && callback.timeout){
609 this._timeOut[o.tId] = window.setTimeout(function(){ oConn.abort(o, callback, true); }, callback.timeout);
612 this._poll[o.tId] = window.setInterval(
614 if(o.conn && o.conn.readyState === 4){
616 // Clear the polling interval for the transaction
617 // and remove the reference from _poll.
618 window.clearInterval(oConn._poll[o.tId]);
619 delete oConn._poll[o.tId];
621 if(callback && callback.timeout){
622 window.clearTimeout(oConn._timeOut[o.tId]);
623 delete oConn._timeOut[o.tId];
626 // Fire global custom event -- completeEvent
627 oConn.completeEvent.fire(o, args);
630 // Fire transaction custom event -- completeEvent
631 o.completeEvent.fire(o, args);
634 oConn.handleTransactionResponse(o, callback);
637 ,this._polling_interval);
641 * @description This method attempts to interpret the server response and
642 * determine whether the transaction was successful, or if an error or
643 * exception was encountered.
644 * @method handleTransactionResponse
647 * @param {object} o The connection object
648 * @param {object} callback The user-defined callback object
649 * @param {boolean} isAbort Determines if the transaction was terminated via abort().
652 handleTransactionResponse:function(o, callback, isAbort)
654 var httpStatus, responseObject;
655 var args = (callback && callback.argument)?callback.argument:null;
659 if(o.conn.status !== undefined && o.conn.status !== 0){
660 httpStatus = o.conn.status;
668 // 13030 is a custom code to indicate the condition -- in Mozilla/FF --
669 // when the XHR object's status and statusText properties are
670 // unavailable, and a query attempt throws an exception.
674 if(httpStatus >= 200 && httpStatus < 300 || httpStatus === 1223){
675 responseObject = this.createResponseObject(o, args);
676 if(callback && callback.success){
678 callback.success(responseObject);
681 // If a scope property is defined, the callback will be fired from
682 // the context of the object.
683 callback.success.apply(callback.scope, [responseObject]);
687 // Fire global custom event -- successEvent
688 this.successEvent.fire(responseObject);
691 // Fire transaction custom event -- successEvent
692 o.successEvent.fire(responseObject);
697 // The following cases are wininet.dll error codes that may be encountered.
698 case 12002: // Server timeout
699 case 12029: // 12029 to 12031 correspond to dropped connections.
702 case 12152: // Connection closed by server.
703 case 13030: // See above comments for variable status.
704 responseObject = this.createExceptionObject(o.tId, args, (isAbort?isAbort:false));
705 if(callback && callback.failure){
707 callback.failure(responseObject);
710 callback.failure.apply(callback.scope, [responseObject]);
716 responseObject = this.createResponseObject(o, args);
717 if(callback && callback.failure){
719 callback.failure(responseObject);
722 callback.failure.apply(callback.scope, [responseObject]);
727 // Fire global custom event -- failureEvent
728 this.failureEvent.fire(responseObject);
731 // Fire transaction custom event -- failureEvent
732 o.failureEvent.fire(responseObject);
737 this.releaseObject(o);
738 responseObject = null;
742 * @description This method evaluates the server response, creates and returns the results via
743 * its properties. Success and failure cases will differ in the response
744 * object's property values.
745 * @method createResponseObject
748 * @param {object} o The connection object
749 * @param {callbackArg} callbackArg The user-defined argument or arguments to be passed to the callback
752 createResponseObject:function(o, callbackArg)
759 var headerStr = o.conn.getAllResponseHeaders();
760 var header = headerStr.split('\n');
761 for(var i=0; i<header.length; i++){
762 var delimitPos = header[i].indexOf(':');
763 if(delimitPos != -1){
764 headerObj[header[i].substring(0,delimitPos)] = header[i].substring(delimitPos+2);
771 // Normalize IE's response to HTTP 204 when Win error 1223.
772 obj.status = (o.conn.status == 1223)?204:o.conn.status;
773 // Normalize IE's statusText to "No Content" instead of "Unknown".
774 obj.statusText = (o.conn.status == 1223)?"No Content":o.conn.statusText;
775 obj.getResponseHeader = headerObj;
776 obj.getAllResponseHeaders = headerStr;
777 obj.responseText = o.conn.responseText;
778 obj.responseXML = o.conn.responseXML;
781 obj.argument = callbackArg;
788 * @description If a transaction cannot be completed due to dropped or closed connections,
789 * there may be not be enough information to build a full response object.
790 * The failure callback will be fired and this specific condition can be identified
791 * by a status property value of 0.
793 * If an abort was successful, the status property will report a value of -1.
795 * @method createExceptionObject
798 * @param {int} tId The Transaction Id
799 * @param {callbackArg} callbackArg The user-defined argument or arguments to be passed to the callback
800 * @param {boolean} isAbort Determines if the exception case is caused by a transaction abort
803 createExceptionObject:function(tId, callbackArg, isAbort)
806 var COMM_ERROR = 'communication failure';
808 var ABORT_ERROR = 'transaction aborted';
814 obj.status = ABORT_CODE;
815 obj.statusText = ABORT_ERROR;
818 obj.status = COMM_CODE;
819 obj.statusText = COMM_ERROR;
823 obj.argument = callbackArg;
830 * @description Method that initializes the custom HTTP headers for the each transaction.
834 * @param {string} label The HTTP header label
835 * @param {string} value The HTTP header value
836 * @param {string} isDefault Determines if the specific header is a default header
837 * automatically sent with each transaction.
840 initHeader:function(label, value, isDefault)
842 var headerObj = (isDefault)?this._default_headers:this._http_headers;
843 headerObj[label] = value;
846 this._has_default_headers = true;
849 this._has_http_headers = true;
855 * @description Accessor that sets the HTTP headers for each transaction.
859 * @param {object} o The connection object for the transaction.
862 setHeader:function(o)
865 if(this._has_default_headers){
866 for(prop in this._default_headers){
867 if(YAHOO.lang.hasOwnProperty(this._default_headers, prop)){
868 o.conn.setRequestHeader(prop, this._default_headers[prop]);
873 if(this._has_http_headers){
874 for(prop in this._http_headers){
875 if(YAHOO.lang.hasOwnProperty(this._http_headers, prop)){
876 o.conn.setRequestHeader(prop, this._http_headers[prop]);
879 delete this._http_headers;
881 this._http_headers = {};
882 this._has_http_headers = false;
887 * @description Resets the default HTTP headers object
888 * @method resetDefaultHeaders
893 resetDefaultHeaders:function(){
894 delete this._default_headers;
895 this._default_headers = {};
896 this._has_default_headers = false;
900 * @description This method assembles the form label and value pairs and
901 * constructs an encoded string.
902 * asyncRequest() will automatically initialize the transaction with a
903 * a HTTP header Content-Type of application/x-www-form-urlencoded.
907 * @param {string || object} form id or name attribute, or form object.
908 * @param {boolean} optional enable file upload.
909 * @param {boolean} optional enable file upload over SSL in IE only.
910 * @return {string} string of the HTML form field name and value pairs..
912 setForm:function(formId, isUpload, secureUri)
914 var oForm, oElement, oName, oValue, oDisabled,
919 this.resetFormState();
921 if(typeof formId == 'string'){
922 // Determine if the argument is a form id or a form name.
923 // Note form name usage is deprecated by supported
924 // here for legacy reasons.
925 oForm = (document.getElementById(formId) || document.forms[formId]);
927 else if(typeof formId == 'object'){
928 // Treat argument as an HTML form object.
935 // If the isUpload argument is true, setForm will call createFrame to initialize
936 // an iframe as the form target.
938 // The argument secureURI is also required by IE in SSL environments
939 // where the secureURI string is a fully qualified HTTP path, used to set the source
940 // of the iframe, to a stub resource in the same domain.
943 // Create iframe in preparation for file upload.
944 this.createFrame(secureUri?secureUri:null);
946 // Set form reference and file upload properties to true.
947 this._isFormSubmit = true;
948 this._isFileUpload = true;
949 this._formNode = oForm;
955 // Iterate over the form elements collection to construct the
956 // label-value pairs.
957 for (i=0,len=oForm.elements.length; i<len; ++i){
958 oElement = oForm.elements[i];
959 oDisabled = oElement.disabled;
960 oName = oElement.name;
962 // Do not submit fields that are disabled or
963 // do not have a name attribute value.
964 if(!oDisabled && oName)
966 oName = encodeURIComponent(oName)+'=';
967 oValue = encodeURIComponent(oElement.value);
969 switch(oElement.type)
971 // Safari, Opera, FF all default opt.value from .text if
972 // value attribute not specified in markup
974 if (oElement.selectedIndex > -1) {
975 opt = oElement.options[oElement.selectedIndex];
976 data[item++] = oName + encodeURIComponent(
977 (opt.attributes.value && opt.attributes.value.specified) ? opt.value : opt.text);
980 case 'select-multiple':
981 if (oElement.selectedIndex > -1) {
982 for(j=oElement.selectedIndex, jlen=oElement.options.length; j<jlen; ++j){
983 opt = oElement.options[j];
985 data[item++] = oName + encodeURIComponent(
986 (opt.attributes.value && opt.attributes.value.specified) ? opt.value : opt.text);
993 if(oElement.checked){
994 data[item++] = oName + oValue;
998 // stub case as XMLHttpRequest will only send the file path as a string.
1000 // stub case for fieldset element which returns undefined.
1002 // stub case for input type reset button.
1004 // stub case for input type button elements.
1007 if(hasSubmit === false){
1008 if(this._hasSubmitListener && this._submitElementValue){
1009 data[item++] = this._submitElementValue;
1015 data[item++] = oName + oValue;
1020 this._isFormSubmit = true;
1021 this._sFormData = data.join('&');
1024 this.initHeader('Content-Type', this._default_form_header);
1026 return this._sFormData;
1030 * @description Resets HTML form properties when an HTML form or HTML form
1031 * with file upload transaction is sent.
1032 * @method resetFormState
1037 resetFormState:function(){
1038 this._isFormSubmit = false;
1039 this._isFileUpload = false;
1040 this._formNode = null;
1041 this._sFormData = "";
1045 * @description Creates an iframe to be used for form file uploads. It is remove from the
1046 * document upon completion of the upload transaction.
1047 * @method createFrame
1050 * @param {string} optional qualified path of iframe resource for SSL in IE.
1053 createFrame:function(secureUri){
1055 // IE does not allow the setting of id and name attributes as object
1056 // properties via createElement(). A different iframe creation
1057 // pattern is required for IE.
1058 var frameId = 'yuiIO' + this._transaction_id;
1060 if(YAHOO.env.ua.ie){
1061 io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
1063 // IE will throw a security exception in an SSL environment if the
1064 // iframe source is undefined.
1065 if(typeof secureUri == 'boolean'){
1066 io.src = 'javascript:false';
1070 io = document.createElement('iframe');
1075 io.style.position = 'absolute';
1076 io.style.top = '-1000px';
1077 io.style.left = '-1000px';
1079 document.body.appendChild(io);
1083 * @description Parses the POST data and creates hidden form elements
1084 * for each key-value, and appends them to the HTML form object.
1085 * @method appendPostData
1088 * @param {string} postData The HTTP POST data
1089 * @return {array} formElements Collection of hidden fields.
1091 appendPostData:function(postData)
1093 var formElements = [],
1094 postMessage = postData.split('&'),
1096 for(i=0; i < postMessage.length; i++){
1097 delimitPos = postMessage[i].indexOf('=');
1098 if(delimitPos != -1){
1099 formElements[i] = document.createElement('input');
1100 formElements[i].type = 'hidden';
1101 formElements[i].name = decodeURIComponent(postMessage[i].substring(0,delimitPos));
1102 formElements[i].value = decodeURIComponent(postMessage[i].substring(delimitPos+1));
1103 this._formNode.appendChild(formElements[i]);
1107 return formElements;
1111 * @description Uploads HTML form, inclusive of files/attachments, using the
1112 * iframe created in createFrame to facilitate the transaction.
1113 * @method uploadFile
1116 * @param {int} id The transaction id.
1117 * @param {object} callback User-defined callback object.
1118 * @param {string} uri Fully qualified path of resource.
1119 * @param {string} postData POST data to be submitted in addition to HTML form.
1122 uploadFile:function(o, callback, uri, postData){
1124 // Each iframe has an id prefix of "yuiIO" followed
1125 // by the unique transaction id.
1126 var frameId = 'yuiIO' + o.tId,
1127 uploadEncoding = 'multipart/form-data',
1128 io = document.getElementById(frameId),
1130 args = (callback && callback.argument)?callback.argument:null,
1131 oElements,i,prop,obj;
1133 // Track original HTML form attribute values.
1134 var rawFormAttributes =
1136 action:this._formNode.getAttribute('action'),
1137 method:this._formNode.getAttribute('method'),
1138 target:this._formNode.getAttribute('target')
1141 // Initialize the HTML form properties in case they are
1142 // not defined in the HTML form.
1143 this._formNode.setAttribute('action', uri);
1144 this._formNode.setAttribute('method', 'POST');
1145 this._formNode.setAttribute('target', frameId);
1147 if(YAHOO.env.ua.ie){
1148 // IE does not respect property enctype for HTML forms.
1149 // Instead it uses the property - "encoding".
1150 this._formNode.setAttribute('encoding', uploadEncoding);
1153 this._formNode.setAttribute('enctype', uploadEncoding);
1157 oElements = this.appendPostData(postData);
1160 // Start file upload.
1161 this._formNode.submit();
1163 // Fire global custom event -- startEvent
1164 this.startEvent.fire(o, args);
1167 // Fire transaction custom event -- startEvent
1168 o.startEvent.fire(o, args);
1171 // Start polling if a callback is present and the timeout
1172 // property has been defined.
1173 if(callback && callback.timeout){
1174 this._timeOut[o.tId] = window.setTimeout(function(){ oConn.abort(o, callback, true); }, callback.timeout);
1177 // Remove HTML elements created by appendPostData
1178 if(oElements && oElements.length > 0){
1179 for(i=0; i < oElements.length; i++){
1180 this._formNode.removeChild(oElements[i]);
1184 // Restore HTML form attributes to their original
1185 // values prior to file upload.
1186 for(prop in rawFormAttributes){
1187 if(YAHOO.lang.hasOwnProperty(rawFormAttributes, prop)){
1188 if(rawFormAttributes[prop]){
1189 this._formNode.setAttribute(prop, rawFormAttributes[prop]);
1192 this._formNode.removeAttribute(prop);
1197 // Reset HTML form state properties.
1198 this.resetFormState();
1200 // Create the upload callback handler that fires when the iframe
1201 // receives the load event. Subsequently, the event handler is detached
1202 // and the iframe removed from the document.
1203 var uploadCallback = function()
1205 if(callback && callback.timeout){
1206 window.clearTimeout(oConn._timeOut[o.tId]);
1207 delete oConn._timeOut[o.tId];
1210 // Fire global custom event -- completeEvent
1211 oConn.completeEvent.fire(o, args);
1213 if(o.completeEvent){
1214 // Fire transaction custom event -- completeEvent
1215 o.completeEvent.fire(o, args);
1220 argument : callback.argument
1225 // responseText and responseXML will be populated with the same data from the iframe.
1226 // Since the HTTP headers cannot be read from the iframe
1227 obj.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:io.contentWindow.document.documentElement.textContent;
1228 obj.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
1232 if(callback && callback.upload){
1233 if(!callback.scope){
1234 callback.upload(obj);
1237 callback.upload.apply(callback.scope, [obj]);
1241 // Fire global custom event -- uploadEvent
1242 oConn.uploadEvent.fire(obj);
1245 // Fire transaction custom event -- uploadEvent
1246 o.uploadEvent.fire(obj);
1249 YAHOO.util.Event.removeListener(io, "load", uploadCallback);
1253 document.body.removeChild(io);
1254 oConn.releaseObject(o);
1258 // Bind the onload handler to the iframe to detect the file upload response.
1259 YAHOO.util.Event.addListener(io, "load", uploadCallback);
1263 * @description Method to terminate a transaction, if it has not reached readyState 4.
1267 * @param {object} o The connection object returned by asyncRequest.
1268 * @param {object} callback User-defined callback object.
1269 * @param {string} isTimeout boolean to indicate if abort resulted from a callback timeout.
1272 abort:function(o, callback, isTimeout)
1275 var args = (callback && callback.argument)?callback.argument:null;
1279 if(this.isCallInProgress(o)){
1280 // Issue abort request
1283 window.clearInterval(this._poll[o.tId]);
1284 delete this._poll[o.tId];
1287 window.clearTimeout(this._timeOut[o.tId]);
1288 delete this._timeOut[o.tId];
1294 else if(o && o.isUpload === true){
1295 var frameId = 'yuiIO' + o.tId;
1296 var io = document.getElementById(frameId);
1299 // Remove all listeners on the iframe prior to
1301 YAHOO.util.Event.removeListener(io, "load");
1302 // Destroy the iframe facilitating the transaction.
1303 document.body.removeChild(io);
1306 window.clearTimeout(this._timeOut[o.tId]);
1307 delete this._timeOut[o.tId];
1314 abortStatus = false;
1317 if(abortStatus === true){
1318 // Fire global custom event -- abortEvent
1319 this.abortEvent.fire(o, args);
1322 // Fire transaction custom event -- abortEvent
1323 o.abortEvent.fire(o, args);
1326 this.handleTransactionResponse(o, callback, true);
1333 * @description Determines if the transaction is still being processed.
1334 * @method isCallInProgress
1337 * @param {object} o The connection object returned by asyncRequest
1340 isCallInProgress:function(o)
1342 // if the XHR object assigned to the transaction has not been dereferenced,
1343 // then check its readyState status. Otherwise, return false.
1345 return o.conn.readyState !== 4 && o.conn.readyState !== 0;
1347 else if(o && o.isUpload === true){
1348 var frameId = 'yuiIO' + o.tId;
1349 return document.getElementById(frameId)?true:false;
1357 * @description Dereference the XHR instance and the connection object after the transaction is completed.
1358 * @method releaseObject
1361 * @param {object} o The connection object
1364 releaseObject:function(o)
1367 //dereference the XHR instance.
1371 //dereference the connection object.
1376 YAHOO.register("connection", YAHOO.util.Connect, {version: "2.7.0", build: "1799"});