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);
336 YAHOO.log('ActiveX Program Id ' + id + ' added to _msxml_progid.', 'info', 'Connection');
340 * @description Member to override the default POST header.
341 * @method setDefaultPostHeader
344 * @param {boolean} b Set and use default header - true or false .
347 setDefaultPostHeader:function(b)
349 if(typeof b == 'string'){
350 this._default_post_header = b;
351 YAHOO.log('Default POST header set to ' + b, 'info', 'Connection');
353 else if(typeof b == 'boolean'){
354 this._use_default_post_header = b;
359 * @description Member to override the default transaction header..
360 * @method setDefaultXhrHeader
363 * @param {boolean} b Set and use default header - true or false .
366 setDefaultXhrHeader:function(b)
368 if(typeof b == 'string'){
369 this._default_xhr_header = b;
370 YAHOO.log('Default XHR header set to ' + b, 'info', 'Connection');
373 this._use_default_xhr_header = b;
378 * @description Member to modify the default polling interval.
379 * @method setPollingInterval
382 * @param {int} i The polling interval in milliseconds.
385 setPollingInterval:function(i)
387 if(typeof i == 'number' && isFinite(i)){
388 this._polling_interval = i;
389 YAHOO.log('Default polling interval set to ' + i +'ms', 'info', 'Connection');
394 * @description Instantiates a XMLHttpRequest object and returns an object with two properties:
395 * the XMLHttpRequest instance and the transaction id.
396 * @method createXhrObject
399 * @param {int} transactionId Property containing the transaction id for this transaction.
402 createXhrObject:function(transactionId)
407 // Instantiates XMLHttpRequest in non-IE browsers and assigns to http.
408 http = new XMLHttpRequest();
409 // Object literal with http and tId properties
410 obj = { conn:http, tId:transactionId };
411 YAHOO.log('XHR object created for transaction ' + transactionId, 'info', 'Connection');
415 for(var i=0; i<this._msxml_progid.length; ++i){
418 // Instantiates XMLHttpRequest for IE and assign to http
419 http = new ActiveXObject(this._msxml_progid[i]);
420 // Object literal with conn and tId properties
421 obj = { conn:http, tId:transactionId };
422 YAHOO.log('ActiveX XHR object created for transaction ' + transactionId, 'info', 'Connection');
435 * @description This method is called by asyncRequest to create a
436 * valid connection object for the transaction. It also passes a
437 * transaction id and increments the transaction id counter.
438 * @method getConnectionObject
443 getConnectionObject:function(isFileUpload)
446 var tId = this._transaction_id;
451 o = this.createXhrObject(tId);
460 this._transaction_id++;
471 * @description Method for initiating an asynchronous request via the XHR object.
472 * @method asyncRequest
475 * @param {string} method HTTP transaction method
476 * @param {string} uri Fully qualified path of resource
477 * @param {callback} callback User-defined callback function or object
478 * @param {string} postData POST body
479 * @return {object} Returns the connection object
481 asyncRequest:function(method, uri, callback, postData)
483 var o = (this._isFileUpload)?this.getConnectionObject(true):this.getConnectionObject();
484 var args = (callback && callback.argument)?callback.argument:null;
487 YAHOO.log('Unable to create connection object.', 'error', 'Connection');
492 // Intialize any transaction-specific custom events, if provided.
493 if(callback && callback.customevents){
494 this.initCustomEvents(o, callback);
497 if(this._isFormSubmit){
498 if(this._isFileUpload){
499 this.uploadFile(o, callback, uri, postData);
503 // If the specified HTTP method is GET, setForm() will return an
504 // encoded string that is concatenated to the uri to
505 // create a querystring.
506 if(method.toUpperCase() == 'GET'){
507 if(this._sFormData.length !== 0){
508 // If the URI already contains a querystring, append an ampersand
509 // and then concatenate _sFormData to the URI.
510 uri += ((uri.indexOf('?') == -1)?'?':'&') + this._sFormData;
513 else if(method.toUpperCase() == 'POST'){
514 // If POST data exist in addition to the HTML form data,
515 // it will be concatenated to the form data.
516 postData = postData?this._sFormData + "&" + postData:this._sFormData;
520 if(method.toUpperCase() == 'GET' && (callback && callback.cache === false)){
521 // If callback.cache is defined and set to false, a
522 // timestamp value will be added to the querystring.
523 uri += ((uri.indexOf('?') == -1)?'?':'&') + "rnd=" + new Date().valueOf().toString();
526 o.conn.open(method, uri, true);
528 // Each transaction will automatically include a custom header of
529 // "X-Requested-With: XMLHttpRequest" to identify the request as
530 // having originated from Connection Manager.
531 if(this._use_default_xhr_header){
532 if(!this._default_headers['X-Requested-With']){
533 this.initHeader('X-Requested-With', this._default_xhr_header, true);
534 YAHOO.log('Initialize transaction header X-Request-Header to XMLHttpRequest.', 'info', 'Connection');
538 //If the transaction method is POST and the POST header value is set to true
539 //or a custom value, initalize the Content-Type header to this value.
540 if((method.toUpperCase() === 'POST' && this._use_default_post_header) && this._isFormSubmit === false){
541 this.initHeader('Content-Type', this._default_post_header);
542 YAHOO.log('Initialize header Content-Type to application/x-www-form-urlencoded; UTF-8 for POST transaction.', 'info', 'Connection');
545 //Initialize all default and custom HTTP headers,
546 if(this._has_default_headers || this._has_http_headers){
550 this.handleReadyState(o, callback);
551 o.conn.send(postData || '');
552 YAHOO.log('Transaction ' + o.tId + ' sent.', 'info', 'Connection');
555 // Reset the HTML form data and state properties as
556 // soon as the data are submitted.
557 if(this._isFormSubmit === true){
558 this.resetFormState();
561 // Fire global custom event -- startEvent
562 this.startEvent.fire(o, args);
565 // Fire transaction custom event -- startEvent
566 o.startEvent.fire(o, args);
574 * @description This method creates and subscribes custom events,
575 * specific to each transaction
576 * @method initCustomEvents
579 * @param {object} o The connection object
580 * @param {callback} callback The user-defined callback object
583 initCustomEvents:function(o, callback)
586 // Enumerate through callback.customevents members and bind/subscribe
587 // events that match in the _customEvents table.
588 for(prop in callback.customevents){
589 if(this._customEvents[prop][0]){
590 // Create the custom event
591 o[this._customEvents[prop][0]] = new YAHOO.util.CustomEvent(this._customEvents[prop][1], (callback.scope)?callback.scope:null);
592 YAHOO.log('Transaction-specific Custom Event ' + o[this._customEvents[prop][1]] + ' created.', 'info', 'Connection');
594 // Subscribe the custom event
595 o[this._customEvents[prop][0]].subscribe(callback.customevents[prop]);
596 YAHOO.log('Transaction-specific Custom Event ' + o[this._customEvents[prop][1]] + ' subscribed.', 'info', 'Connection');
602 * @description This method serves as a timer that polls the XHR object's readyState
603 * property during a transaction, instead of binding a callback to the
604 * onreadystatechange event. Upon readyState 4, handleTransactionResponse
605 * will process the response, and the timer will be cleared.
606 * @method handleReadyState
609 * @param {object} o The connection object
610 * @param {callback} callback The user-defined callback object
614 handleReadyState:function(o, callback)
618 var args = (callback && callback.argument)?callback.argument:null;
620 if(callback && callback.timeout){
621 this._timeOut[o.tId] = window.setTimeout(function(){ oConn.abort(o, callback, true); }, callback.timeout);
624 this._poll[o.tId] = window.setInterval(
626 if(o.conn && o.conn.readyState === 4){
628 // Clear the polling interval for the transaction
629 // and remove the reference from _poll.
630 window.clearInterval(oConn._poll[o.tId]);
631 delete oConn._poll[o.tId];
633 if(callback && callback.timeout){
634 window.clearTimeout(oConn._timeOut[o.tId]);
635 delete oConn._timeOut[o.tId];
638 // Fire global custom event -- completeEvent
639 oConn.completeEvent.fire(o, args);
642 // Fire transaction custom event -- completeEvent
643 o.completeEvent.fire(o, args);
646 oConn.handleTransactionResponse(o, callback);
649 ,this._polling_interval);
653 * @description This method attempts to interpret the server response and
654 * determine whether the transaction was successful, or if an error or
655 * exception was encountered.
656 * @method handleTransactionResponse
659 * @param {object} o The connection object
660 * @param {object} callback The user-defined callback object
661 * @param {boolean} isAbort Determines if the transaction was terminated via abort().
664 handleTransactionResponse:function(o, callback, isAbort)
666 var httpStatus, responseObject;
667 var args = (callback && callback.argument)?callback.argument:null;
671 if(o.conn.status !== undefined && o.conn.status !== 0){
672 httpStatus = o.conn.status;
680 // 13030 is a custom code to indicate the condition -- in Mozilla/FF --
681 // when the XHR object's status and statusText properties are
682 // unavailable, and a query attempt throws an exception.
686 if(httpStatus >= 200 && httpStatus < 300 || httpStatus === 1223){
687 responseObject = this.createResponseObject(o, args);
688 if(callback && callback.success){
690 callback.success(responseObject);
691 YAHOO.log('Success callback. HTTP code is ' + httpStatus, 'info', 'Connection');
694 // If a scope property is defined, the callback will be fired from
695 // the context of the object.
696 callback.success.apply(callback.scope, [responseObject]);
697 YAHOO.log('Success callback with scope. HTTP code is ' + httpStatus, 'info', 'Connection');
701 // Fire global custom event -- successEvent
702 this.successEvent.fire(responseObject);
705 // Fire transaction custom event -- successEvent
706 o.successEvent.fire(responseObject);
711 // The following cases are wininet.dll error codes that may be encountered.
712 case 12002: // Server timeout
713 case 12029: // 12029 to 12031 correspond to dropped connections.
716 case 12152: // Connection closed by server.
717 case 13030: // See above comments for variable status.
718 responseObject = this.createExceptionObject(o.tId, args, (isAbort?isAbort:false));
719 if(callback && callback.failure){
721 callback.failure(responseObject);
722 YAHOO.log('Failure callback. Exception detected. Status code is ' + httpStatus, 'warn', 'Connection');
725 callback.failure.apply(callback.scope, [responseObject]);
726 YAHOO.log('Failure callback with scope. Exception detected. Status code is ' + httpStatus, 'warn', 'Connection');
732 responseObject = this.createResponseObject(o, args);
733 if(callback && callback.failure){
735 callback.failure(responseObject);
736 YAHOO.log('Failure callback. HTTP status code is ' + httpStatus, 'warn', 'Connection');
739 callback.failure.apply(callback.scope, [responseObject]);
740 YAHOO.log('Failure callback with scope. HTTP status code is ' + httpStatus, 'warn', 'Connection');
745 // Fire global custom event -- failureEvent
746 this.failureEvent.fire(responseObject);
749 // Fire transaction custom event -- failureEvent
750 o.failureEvent.fire(responseObject);
755 this.releaseObject(o);
756 responseObject = null;
760 * @description This method evaluates the server response, creates and returns the results via
761 * its properties. Success and failure cases will differ in the response
762 * object's property values.
763 * @method createResponseObject
766 * @param {object} o The connection object
767 * @param {callbackArg} callbackArg The user-defined argument or arguments to be passed to the callback
770 createResponseObject:function(o, callbackArg)
777 var headerStr = o.conn.getAllResponseHeaders();
778 var header = headerStr.split('\n');
779 for(var i=0; i<header.length; i++){
780 var delimitPos = header[i].indexOf(':');
781 if(delimitPos != -1){
782 headerObj[header[i].substring(0,delimitPos)] = header[i].substring(delimitPos+2);
789 // Normalize IE's response to HTTP 204 when Win error 1223.
790 obj.status = (o.conn.status == 1223)?204:o.conn.status;
791 // Normalize IE's statusText to "No Content" instead of "Unknown".
792 obj.statusText = (o.conn.status == 1223)?"No Content":o.conn.statusText;
793 obj.getResponseHeader = headerObj;
794 obj.getAllResponseHeaders = headerStr;
795 obj.responseText = o.conn.responseText;
796 obj.responseXML = o.conn.responseXML;
799 obj.argument = callbackArg;
806 * @description If a transaction cannot be completed due to dropped or closed connections,
807 * there may be not be enough information to build a full response object.
808 * The failure callback will be fired and this specific condition can be identified
809 * by a status property value of 0.
811 * If an abort was successful, the status property will report a value of -1.
813 * @method createExceptionObject
816 * @param {int} tId The Transaction Id
817 * @param {callbackArg} callbackArg The user-defined argument or arguments to be passed to the callback
818 * @param {boolean} isAbort Determines if the exception case is caused by a transaction abort
821 createExceptionObject:function(tId, callbackArg, isAbort)
824 var COMM_ERROR = 'communication failure';
826 var ABORT_ERROR = 'transaction aborted';
832 obj.status = ABORT_CODE;
833 obj.statusText = ABORT_ERROR;
836 obj.status = COMM_CODE;
837 obj.statusText = COMM_ERROR;
841 obj.argument = callbackArg;
848 * @description Method that initializes the custom HTTP headers for the each transaction.
852 * @param {string} label The HTTP header label
853 * @param {string} value The HTTP header value
854 * @param {string} isDefault Determines if the specific header is a default header
855 * automatically sent with each transaction.
858 initHeader:function(label, value, isDefault)
860 var headerObj = (isDefault)?this._default_headers:this._http_headers;
861 headerObj[label] = value;
864 this._has_default_headers = true;
867 this._has_http_headers = true;
873 * @description Accessor that sets the HTTP headers for each transaction.
877 * @param {object} o The connection object for the transaction.
880 setHeader:function(o)
883 if(this._has_default_headers){
884 for(prop in this._default_headers){
885 if(YAHOO.lang.hasOwnProperty(this._default_headers, prop)){
886 o.conn.setRequestHeader(prop, this._default_headers[prop]);
887 YAHOO.log('Default HTTP header ' + prop + ' set with value of ' + this._default_headers[prop], 'info', 'Connection');
892 if(this._has_http_headers){
893 for(prop in this._http_headers){
894 if(YAHOO.lang.hasOwnProperty(this._http_headers, prop)){
895 o.conn.setRequestHeader(prop, this._http_headers[prop]);
896 YAHOO.log('HTTP header ' + prop + ' set with value of ' + this._http_headers[prop], 'info', 'Connection');
899 delete this._http_headers;
901 this._http_headers = {};
902 this._has_http_headers = false;
907 * @description Resets the default HTTP headers object
908 * @method resetDefaultHeaders
913 resetDefaultHeaders:function(){
914 delete this._default_headers;
915 this._default_headers = {};
916 this._has_default_headers = false;
920 * @description This method assembles the form label and value pairs and
921 * constructs an encoded string.
922 * asyncRequest() will automatically initialize the transaction with a
923 * a HTTP header Content-Type of application/x-www-form-urlencoded.
927 * @param {string || object} form id or name attribute, or form object.
928 * @param {boolean} optional enable file upload.
929 * @param {boolean} optional enable file upload over SSL in IE only.
930 * @return {string} string of the HTML form field name and value pairs..
932 setForm:function(formId, isUpload, secureUri)
934 var oForm, oElement, oName, oValue, oDisabled,
939 this.resetFormState();
941 if(typeof formId == 'string'){
942 // Determine if the argument is a form id or a form name.
943 // Note form name usage is deprecated by supported
944 // here for legacy reasons.
945 oForm = (document.getElementById(formId) || document.forms[formId]);
947 else if(typeof formId == 'object'){
948 // Treat argument as an HTML form object.
952 YAHOO.log('Unable to create form object ' + formId, 'warn', 'Connection');
956 // If the isUpload argument is true, setForm will call createFrame to initialize
957 // an iframe as the form target.
959 // The argument secureURI is also required by IE in SSL environments
960 // where the secureURI string is a fully qualified HTTP path, used to set the source
961 // of the iframe, to a stub resource in the same domain.
964 // Create iframe in preparation for file upload.
965 this.createFrame(secureUri?secureUri:null);
967 // Set form reference and file upload properties to true.
968 this._isFormSubmit = true;
969 this._isFileUpload = true;
970 this._formNode = oForm;
976 // Iterate over the form elements collection to construct the
977 // label-value pairs.
978 for (i=0,len=oForm.elements.length; i<len; ++i){
979 oElement = oForm.elements[i];
980 oDisabled = oElement.disabled;
981 oName = oElement.name;
983 // Do not submit fields that are disabled or
984 // do not have a name attribute value.
985 if(!oDisabled && oName)
987 oName = encodeURIComponent(oName)+'=';
988 oValue = encodeURIComponent(oElement.value);
990 switch(oElement.type)
992 // Safari, Opera, FF all default opt.value from .text if
993 // value attribute not specified in markup
995 if (oElement.selectedIndex > -1) {
996 opt = oElement.options[oElement.selectedIndex];
997 data[item++] = oName + encodeURIComponent(
998 (opt.attributes.value && opt.attributes.value.specified) ? opt.value : opt.text);
1001 case 'select-multiple':
1002 if (oElement.selectedIndex > -1) {
1003 for(j=oElement.selectedIndex, jlen=oElement.options.length; j<jlen; ++j){
1004 opt = oElement.options[j];
1006 data[item++] = oName + encodeURIComponent(
1007 (opt.attributes.value && opt.attributes.value.specified) ? opt.value : opt.text);
1014 if(oElement.checked){
1015 data[item++] = oName + oValue;
1019 // stub case as XMLHttpRequest will only send the file path as a string.
1021 // stub case for fieldset element which returns undefined.
1023 // stub case for input type reset button.
1025 // stub case for input type button elements.
1028 if(hasSubmit === false){
1029 if(this._hasSubmitListener && this._submitElementValue){
1030 data[item++] = this._submitElementValue;
1036 data[item++] = oName + oValue;
1041 this._isFormSubmit = true;
1042 this._sFormData = data.join('&');
1044 YAHOO.log('Form initialized for transaction. HTML form POST message is: ' + this._sFormData, 'info', 'Connection');
1046 this.initHeader('Content-Type', this._default_form_header);
1047 YAHOO.log('Initialize header Content-Type to application/x-www-form-urlencoded for setForm() transaction.', 'info', 'Connection');
1049 return this._sFormData;
1053 * @description Resets HTML form properties when an HTML form or HTML form
1054 * with file upload transaction is sent.
1055 * @method resetFormState
1060 resetFormState:function(){
1061 this._isFormSubmit = false;
1062 this._isFileUpload = false;
1063 this._formNode = null;
1064 this._sFormData = "";
1068 * @description Creates an iframe to be used for form file uploads. It is remove from the
1069 * document upon completion of the upload transaction.
1070 * @method createFrame
1073 * @param {string} optional qualified path of iframe resource for SSL in IE.
1076 createFrame:function(secureUri){
1078 // IE does not allow the setting of id and name attributes as object
1079 // properties via createElement(). A different iframe creation
1080 // pattern is required for IE.
1081 var frameId = 'yuiIO' + this._transaction_id;
1083 if(YAHOO.env.ua.ie){
1084 io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
1086 // IE will throw a security exception in an SSL environment if the
1087 // iframe source is undefined.
1088 if(typeof secureUri == 'boolean'){
1089 io.src = 'javascript:false';
1093 io = document.createElement('iframe');
1098 io.style.position = 'absolute';
1099 io.style.top = '-1000px';
1100 io.style.left = '-1000px';
1102 document.body.appendChild(io);
1103 YAHOO.log('File upload iframe created. Id is:' + frameId, 'info', 'Connection');
1107 * @description Parses the POST data and creates hidden form elements
1108 * for each key-value, and appends them to the HTML form object.
1109 * @method appendPostData
1112 * @param {string} postData The HTTP POST data
1113 * @return {array} formElements Collection of hidden fields.
1115 appendPostData:function(postData)
1117 var formElements = [],
1118 postMessage = postData.split('&'),
1120 for(i=0; i < postMessage.length; i++){
1121 delimitPos = postMessage[i].indexOf('=');
1122 if(delimitPos != -1){
1123 formElements[i] = document.createElement('input');
1124 formElements[i].type = 'hidden';
1125 formElements[i].name = decodeURIComponent(postMessage[i].substring(0,delimitPos));
1126 formElements[i].value = decodeURIComponent(postMessage[i].substring(delimitPos+1));
1127 this._formNode.appendChild(formElements[i]);
1131 return formElements;
1135 * @description Uploads HTML form, inclusive of files/attachments, using the
1136 * iframe created in createFrame to facilitate the transaction.
1137 * @method uploadFile
1140 * @param {int} id The transaction id.
1141 * @param {object} callback User-defined callback object.
1142 * @param {string} uri Fully qualified path of resource.
1143 * @param {string} postData POST data to be submitted in addition to HTML form.
1146 uploadFile:function(o, callback, uri, postData){
1148 // Each iframe has an id prefix of "yuiIO" followed
1149 // by the unique transaction id.
1150 var frameId = 'yuiIO' + o.tId,
1151 uploadEncoding = 'multipart/form-data',
1152 io = document.getElementById(frameId),
1154 args = (callback && callback.argument)?callback.argument:null,
1155 oElements,i,prop,obj;
1157 // Track original HTML form attribute values.
1158 var rawFormAttributes =
1160 action:this._formNode.getAttribute('action'),
1161 method:this._formNode.getAttribute('method'),
1162 target:this._formNode.getAttribute('target')
1165 // Initialize the HTML form properties in case they are
1166 // not defined in the HTML form.
1167 this._formNode.setAttribute('action', uri);
1168 this._formNode.setAttribute('method', 'POST');
1169 this._formNode.setAttribute('target', frameId);
1171 if(YAHOO.env.ua.ie){
1172 // IE does not respect property enctype for HTML forms.
1173 // Instead it uses the property - "encoding".
1174 this._formNode.setAttribute('encoding', uploadEncoding);
1177 this._formNode.setAttribute('enctype', uploadEncoding);
1181 oElements = this.appendPostData(postData);
1184 // Start file upload.
1185 this._formNode.submit();
1187 // Fire global custom event -- startEvent
1188 this.startEvent.fire(o, args);
1191 // Fire transaction custom event -- startEvent
1192 o.startEvent.fire(o, args);
1195 // Start polling if a callback is present and the timeout
1196 // property has been defined.
1197 if(callback && callback.timeout){
1198 this._timeOut[o.tId] = window.setTimeout(function(){ oConn.abort(o, callback, true); }, callback.timeout);
1201 // Remove HTML elements created by appendPostData
1202 if(oElements && oElements.length > 0){
1203 for(i=0; i < oElements.length; i++){
1204 this._formNode.removeChild(oElements[i]);
1208 // Restore HTML form attributes to their original
1209 // values prior to file upload.
1210 for(prop in rawFormAttributes){
1211 if(YAHOO.lang.hasOwnProperty(rawFormAttributes, prop)){
1212 if(rawFormAttributes[prop]){
1213 this._formNode.setAttribute(prop, rawFormAttributes[prop]);
1216 this._formNode.removeAttribute(prop);
1221 // Reset HTML form state properties.
1222 this.resetFormState();
1224 // Create the upload callback handler that fires when the iframe
1225 // receives the load event. Subsequently, the event handler is detached
1226 // and the iframe removed from the document.
1227 var uploadCallback = function()
1229 if(callback && callback.timeout){
1230 window.clearTimeout(oConn._timeOut[o.tId]);
1231 delete oConn._timeOut[o.tId];
1234 // Fire global custom event -- completeEvent
1235 oConn.completeEvent.fire(o, args);
1237 if(o.completeEvent){
1238 // Fire transaction custom event -- completeEvent
1239 o.completeEvent.fire(o, args);
1244 argument : callback.argument
1249 // responseText and responseXML will be populated with the same data from the iframe.
1250 // Since the HTTP headers cannot be read from the iframe
1251 obj.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:io.contentWindow.document.documentElement.textContent;
1252 obj.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
1256 if(callback && callback.upload){
1257 if(!callback.scope){
1258 callback.upload(obj);
1259 YAHOO.log('Upload callback.', 'info', 'Connection');
1262 callback.upload.apply(callback.scope, [obj]);
1263 YAHOO.log('Upload callback with scope.', 'info', 'Connection');
1267 // Fire global custom event -- uploadEvent
1268 oConn.uploadEvent.fire(obj);
1271 // Fire transaction custom event -- uploadEvent
1272 o.uploadEvent.fire(obj);
1275 YAHOO.util.Event.removeListener(io, "load", uploadCallback);
1279 document.body.removeChild(io);
1280 oConn.releaseObject(o);
1281 YAHOO.log('File upload iframe destroyed. Id is:' + frameId, 'info', 'Connection');
1285 // Bind the onload handler to the iframe to detect the file upload response.
1286 YAHOO.util.Event.addListener(io, "load", uploadCallback);
1290 * @description Method to terminate a transaction, if it has not reached readyState 4.
1294 * @param {object} o The connection object returned by asyncRequest.
1295 * @param {object} callback User-defined callback object.
1296 * @param {string} isTimeout boolean to indicate if abort resulted from a callback timeout.
1299 abort:function(o, callback, isTimeout)
1302 var args = (callback && callback.argument)?callback.argument:null;
1306 if(this.isCallInProgress(o)){
1307 // Issue abort request
1310 window.clearInterval(this._poll[o.tId]);
1311 delete this._poll[o.tId];
1314 window.clearTimeout(this._timeOut[o.tId]);
1315 delete this._timeOut[o.tId];
1321 else if(o && o.isUpload === true){
1322 var frameId = 'yuiIO' + o.tId;
1323 var io = document.getElementById(frameId);
1326 // Remove all listeners on the iframe prior to
1328 YAHOO.util.Event.removeListener(io, "load");
1329 // Destroy the iframe facilitating the transaction.
1330 document.body.removeChild(io);
1331 YAHOO.log('File upload iframe destroyed. Id is:' + frameId, 'info', 'Connection');
1334 window.clearTimeout(this._timeOut[o.tId]);
1335 delete this._timeOut[o.tId];
1342 abortStatus = false;
1345 if(abortStatus === true){
1346 // Fire global custom event -- abortEvent
1347 this.abortEvent.fire(o, args);
1350 // Fire transaction custom event -- abortEvent
1351 o.abortEvent.fire(o, args);
1354 this.handleTransactionResponse(o, callback, true);
1355 YAHOO.log('Transaction ' + o.tId + ' aborted.', 'info', 'Connection');
1362 * @description Determines if the transaction is still being processed.
1363 * @method isCallInProgress
1366 * @param {object} o The connection object returned by asyncRequest
1369 isCallInProgress:function(o)
1371 // if the XHR object assigned to the transaction has not been dereferenced,
1372 // then check its readyState status. Otherwise, return false.
1374 return o.conn.readyState !== 4 && o.conn.readyState !== 0;
1376 else if(o && o.isUpload === true){
1377 var frameId = 'yuiIO' + o.tId;
1378 return document.getElementById(frameId)?true:false;
1386 * @description Dereference the XHR instance and the connection object after the transaction is completed.
1387 * @method releaseObject
1390 * @param {object} o The connection object
1393 releaseObject:function(o)
1396 //dereference the XHR instance.
1399 YAHOO.log('Connection object for transaction ' + o.tId + ' destroyed.', 'info', 'Connection');
1401 //dereference the connection object.
1406 YAHOO.register("connection", YAHOO.util.Connect, {version: "2.7.0", build: "1799"});