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