Merge branch 'master' of http://git.roojs.com/roojs1
[roojs1] / Roo / data / Connection.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11
12  
13
14 /**
15  * @class Roo.data.Connection
16  * @extends Roo.util.Observable
17  * The class encapsulates a connection to the page's originating domain, allowing requests to be made
18  * either to a configured URL, or to a URL specified at request time. 
19  * 
20  * Requests made by this class are asynchronous, and will return immediately. No data from
21  * the server will be available to the statement immediately following the {@link #request} call.
22  * To process returned data, use a callback in the request options object, or an event listener.
23  * 
24  * Note: If you are doing a file upload, you will not get a normal response object sent back to
25  * your callback or event handler.  Since the upload is handled via in IFRAME, there is no XMLHttpRequest.
26  * The response object is created using the innerHTML of the IFRAME's document as the responseText
27  * property and, if present, the IFRAME's XML document as the responseXML property.
28  * 
29  * This means that a valid XML or HTML document must be returned. If JSON data is required, it is suggested
30  * that it be placed either inside a &lt;textarea> in an HTML document and retrieved from the responseText
31  * using a regex, or inside a CDATA section in an XML document and retrieved from the responseXML using
32  * standard DOM methods.
33  * @constructor
34  * @param {Object} config a configuration object.
35  */
36 Roo.data.Connection = function(config){
37     Roo.apply(this, config);
38     this.addEvents({
39         /**
40          * @event beforerequest
41          * Fires before a network request is made to retrieve a data object.
42          * @param {Connection} conn This Connection object.
43          * @param {Object} options The options config object passed to the {@link #request} method.
44          */
45         "beforerequest" : true,
46         /**
47          * @event requestcomplete
48          * Fires if the request was successfully completed.
49          * @param {Connection} conn This Connection object.
50          * @param {Object} response The XHR object containing the response data.
51          * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
52          * @param {Object} options The options config object passed to the {@link #request} method.
53          */
54         "requestcomplete" : true,
55         /**
56          * @event requestexception
57          * Fires if an error HTTP status was returned from the server.
58          * See {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html} for details of HTTP status codes.
59          * @param {Connection} conn This Connection object.
60          * @param {Object} response The XHR object containing the response data.
61          * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
62          * @param {Object} options The options config object passed to the {@link #request} method.
63          */
64         "requestexception" : true
65     });
66     Roo.data.Connection.superclass.constructor.call(this);
67 };
68
69 Roo.extend(Roo.data.Connection, Roo.util.Observable, {
70     /**
71      * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
72      */
73     /**
74      * @cfg {Object} extraParams (Optional) An object containing properties which are used as
75      * extra parameters to each request made by this object. (defaults to undefined)
76      */
77     /**
78      * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
79      *  to each request made by this object. (defaults to undefined)
80      */
81     /**
82      * @cfg {String} method (Optional) The default HTTP method to be used for requests. (defaults to undefined; if not set but parms are present will use POST, otherwise GET)
83      */
84     /**
85      * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
86      */
87     timeout : 30000,
88     /**
89      * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
90      * @type Boolean
91      */
92     autoAbort:false,
93
94     /**
95      * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
96      * @type Boolean
97      */
98     disableCaching: true,
99
100     /**
101      * Sends an HTTP request to a remote server.
102      * @param {Object} options An object which may contain the following properties:<ul>
103      * <li><b>url</b> {String} (Optional) The URL to which to send the request. Defaults to configured URL</li>
104      * <li><b>params</b> {Object/String/Function} (Optional) An object containing properties which are used as parameters to the
105      * request, a url encoded string or a function to call to get either.</li>
106      * <li><b>method</b> {String} (Optional) The HTTP method to use for the request. Defaults to the configured method, or
107      * if no method was configured, "GET" if no parameters are being sent, and "POST" if parameters are being sent.</li>
108      * <li><b>callback</b> {Function} (Optional) The function to be called upon receipt of the HTTP response.
109      * The callback is called regardless of success or failure and is passed the following parameters:<ul>
110      * <li>options {Object} The parameter to the request call.</li>
111      * <li>success {Boolean} True if the request succeeded.</li>
112      * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
113      * </ul></li>
114      * <li><b>success</b> {Function} (Optional) The function to be called upon success of the request.
115      * The callback is passed the following parameters:<ul>
116      * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
117      * <li>options {Object} The parameter to the request call.</li>
118      * </ul></li>
119      * <li><b>failure</b> {Function} (Optional) The function to be called upon failure of the request.
120      * The callback is passed the following parameters:<ul>
121      * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
122      * <li>options {Object} The parameter to the request call.</li>
123      * </ul></li>
124      * <li><b>scope</b> {Object} (Optional) The scope in which to execute the callbacks: The "this" object
125      * for the callback function. Defaults to the browser window.</li>
126      * <li><b>form</b> {Object/String} (Optional) A form object or id to pull parameters from.</li>
127      * <li><b>isUpload</b> {Boolean} (Optional) True if the form object is a file upload (will usually be automatically detected).</li>
128      * <li><b>headers</b> {Object} (Optional) Request headers to set for the request.</li>
129      * <li><b>xmlData</b> {Object} (Optional) XML document to use for the post. Note: This will be used instead of
130      * params for the post data. Any params will be appended to the URL.</li>
131      * <li><b>disableCaching</b> {Boolean} (Optional) True to add a unique cache-buster param to GET requests.</li>
132      * </ul>
133      * @return {Number} transactionId
134      */
135     request : function(o){
136         if(this.fireEvent("beforerequest", this, o) !== false){
137             var p = o.params;
138
139             if(typeof p == "function"){
140                 p = p.call(o.scope||window, o);
141             }
142             if(typeof p == "object"){
143                 p = Roo.urlEncode(o.params);
144             }
145             if(this.extraParams){
146                 var extras = Roo.urlEncode(this.extraParams);
147                 p = p ? (p + '&' + extras) : extras;
148             }
149
150             var url = o.url || this.url;
151             if(typeof url == 'function'){
152                 url = url.call(o.scope||window, o);
153             }
154
155             if(o.form){
156                 var form = Roo.getDom(o.form);
157                 url = url || form.action;
158
159                 var enctype = form.getAttribute("enctype");
160                 
161                 if (o.formData) {
162                     return this.doFormDataUpload(o, url);
163                 }
164                 
165                 if(o.isUpload || (enctype && enctype.toLowerCase() == 'multipart/form-data')){
166                     return this.doFormUpload(o, p, url);
167                 }
168                 var f = Roo.lib.Ajax.serializeForm(form);
169                 p = p ? (p + '&' + f) : f;
170             }
171             
172             if (!o.form && o.formData) {
173                 o.formData = o.formData === true ? new FormData() : o.formData;
174                 for (var k in o.params) {
175                     o.formData.append(k,o.params[k]);
176                 }
177                     
178                 return this.doFormDataUpload(o, url);
179             }
180             
181
182             var hs = o.headers;
183             if(this.defaultHeaders){
184                 hs = Roo.apply(hs || {}, this.defaultHeaders);
185                 if(!o.headers){
186                     o.headers = hs;
187                 }
188             }
189
190             var cb = {
191                 success: this.handleResponse,
192                 failure: this.handleFailure,
193                 scope: this,
194                 argument: {options: o},
195                 timeout : o.timeout || this.timeout
196             };
197
198             var method = o.method||this.method||(p ? "POST" : "GET");
199
200             if(method == 'GET' && (this.disableCaching && o.disableCaching !== false) || o.disableCaching === true){
201                 url += (url.indexOf('?') != -1 ? '&' : '?') + '_dc=' + (new Date().getTime());
202             }
203
204             if(typeof o.autoAbort == 'boolean'){ // options gets top priority
205                 if(o.autoAbort){
206                     this.abort();
207                 }
208             }else if(this.autoAbort !== false){
209                 this.abort();
210             }
211
212             if((method == 'GET' && p) || o.xmlData){
213                 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
214                 p = '';
215             }
216             Roo.lib.Ajax.useDefaultHeader = typeof(o.headers) == 'undefined' || typeof(o.headers['Content-Type']) == 'undefined';
217             this.transId = Roo.lib.Ajax.request(method, url, cb, p, o);
218             Roo.lib.Ajax.useDefaultHeader == true;
219             return this.transId;
220         }else{
221             Roo.callback(o.callback, o.scope, [o, null, null]);
222             return null;
223         }
224     },
225
226     /**
227      * Determine whether this object has a request outstanding.
228      * @param {Number} transactionId (Optional) defaults to the last transaction
229      * @return {Boolean} True if there is an outstanding request.
230      */
231     isLoading : function(transId){
232         if(transId){
233             return Roo.lib.Ajax.isCallInProgress(transId);
234         }else{
235             return this.transId ? true : false;
236         }
237     },
238
239     /**
240      * Aborts any outstanding request.
241      * @param {Number} transactionId (Optional) defaults to the last transaction
242      */
243     abort : function(transId){
244         if(transId || this.isLoading()){
245             Roo.lib.Ajax.abort(transId || this.transId);
246         }
247     },
248
249     // private
250     handleResponse : function(response){
251         this.transId = false;
252         var options = response.argument.options;
253         response.argument = options ? options.argument : null;
254         this.fireEvent("requestcomplete", this, response, options);
255         Roo.callback(options.success, options.scope, [response, options]);
256         Roo.callback(options.callback, options.scope, [options, true, response]);
257     },
258
259     // private
260     handleFailure : function(response, e){
261         this.transId = false;
262         var options = response.argument.options;
263         response.argument = options ? options.argument : null;
264         this.fireEvent("requestexception", this, response, options, e);
265         Roo.callback(options.failure, options.scope, [response, options]);
266         Roo.callback(options.callback, options.scope, [options, false, response]);
267     },
268
269     // private
270     doFormUpload : function(o, ps, url){
271         var id = Roo.id();
272         var frame = document.createElement('iframe');
273         frame.id = id;
274         frame.name = id;
275         frame.className = 'x-hidden';
276         if(Roo.isIE){
277             frame.src = Roo.SSL_SECURE_URL;
278         }
279         document.body.appendChild(frame);
280
281         if(Roo.isIE){
282            document.frames[id].name = id;
283         }
284
285         var form = Roo.getDom(o.form);
286         form.target = id;
287         form.method = 'POST';
288         form.enctype = form.encoding = 'multipart/form-data';
289         if(url){
290             form.action = url;
291         }
292
293         var hiddens, hd;
294         if(ps){ // add dynamic params
295             hiddens = [];
296             ps = Roo.urlDecode(ps, false);
297             for(var k in ps){
298                 if(ps.hasOwnProperty(k)){
299                     hd = document.createElement('input');
300                     hd.type = 'hidden';
301                     hd.name = k;
302                     hd.value = ps[k];
303                     form.appendChild(hd);
304                     hiddens.push(hd);
305                 }
306             }
307         }
308
309         function cb(){
310             var r = {  // bogus response object
311                 responseText : '',
312                 responseXML : null
313             };
314
315             r.argument = o ? o.argument : null;
316
317             try { //
318                 var doc;
319                 if(Roo.isIE){
320                     doc = frame.contentWindow.document;
321                 }else {
322                     doc = (frame.contentDocument || window.frames[id].document);
323                 }
324                 if(doc && doc.body){
325                     r.responseText = doc.body.innerHTML;
326                 }
327                 if(doc && doc.XMLDocument){
328                     r.responseXML = doc.XMLDocument;
329                 }else {
330                     r.responseXML = doc;
331                 }
332             }
333             catch(e) {
334                 // ignore
335             }
336
337             Roo.EventManager.removeListener(frame, 'load', cb, this);
338
339             this.fireEvent("requestcomplete", this, r, o);
340             Roo.callback(o.success, o.scope, [r, o]);
341             Roo.callback(o.callback, o.scope, [o, true, r]);
342
343             setTimeout(function(){document.body.removeChild(frame);}, 100);
344         }
345
346         Roo.EventManager.on(frame, 'load', cb, this);
347         form.submit();
348
349         if(hiddens){ // remove dynamic params
350             for(var i = 0, len = hiddens.length; i < len; i++){
351                 form.removeChild(hiddens[i]);
352             }
353         }
354     },
355     // this is a 'formdata version???'
356     
357     
358     doFormDataUpload : function(o,  url)
359     {
360         var formData;
361         if (o.form) {
362             var form =  Roo.getDom(o.form);
363             form.enctype = form.encoding = 'multipart/form-data';
364             formData = o.formData === true ? new FormData(form) : o.formData;
365         } else {
366             formData = o.formData === true ? new FormData() : o.formData;
367         }
368         
369       
370         var cb = {
371             success: this.handleResponse,
372             failure: this.handleFailure,
373             scope: this,
374             argument: {options: o},
375             timeout : o.timeout || this.timeout
376         };
377  
378         if(typeof o.autoAbort == 'boolean'){ // options gets top priority
379             if(o.autoAbort){
380                 this.abort();
381             }
382         }else if(this.autoAbort !== false){
383             this.abort();
384         }
385
386         //Roo.lib.Ajax.defaultPostHeader = null;
387         Roo.lib.Ajax.useDefaultHeader = false;
388         this.transId = Roo.lib.Ajax.request( "POST", url, cb,  formData, o);
389         Roo.lib.Ajax.useDefaultHeader = true;
390  
391          
392     }
393     
394 });