allow override of content type to affect headers
[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,p,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             var hs = o.headers;
173             if(this.defaultHeaders){
174                 hs = Roo.apply(hs || {}, this.defaultHeaders);
175                 if(!o.headers){
176                     o.headers = hs;
177                 }
178             }
179
180             var cb = {
181                 success: this.handleResponse,
182                 failure: this.handleFailure,
183                 scope: this,
184                 argument: {options: o},
185                 timeout : o.timeout || this.timeout
186             };
187
188             var method = o.method||this.method||(p ? "POST" : "GET");
189
190             if(method == 'GET' && (this.disableCaching && o.disableCaching !== false) || o.disableCaching === true){
191                 url += (url.indexOf('?') != -1 ? '&' : '?') + '_dc=' + (new Date().getTime());
192             }
193
194             if(typeof o.autoAbort == 'boolean'){ // options gets top priority
195                 if(o.autoAbort){
196                     this.abort();
197                 }
198             }else if(this.autoAbort !== false){
199                 this.abort();
200             }
201
202             if((method == 'GET' && p) || o.xmlData){
203                 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
204                 p = '';
205             }
206             Roo.lib.Ajax.useDefaultHeader == typeof(o.headers['Content-Type']) == 'undefined';
207             this.transId = Roo.lib.Ajax.request(method, url, cb, p, o);
208             Roo.lib.Ajax.useDefaultHeader == true;
209             return this.transId;
210         }else{
211             Roo.callback(o.callback, o.scope, [o, null, null]);
212             return null;
213         }
214     },
215
216     /**
217      * Determine whether this object has a request outstanding.
218      * @param {Number} transactionId (Optional) defaults to the last transaction
219      * @return {Boolean} True if there is an outstanding request.
220      */
221     isLoading : function(transId){
222         if(transId){
223             return Roo.lib.Ajax.isCallInProgress(transId);
224         }else{
225             return this.transId ? true : false;
226         }
227     },
228
229     /**
230      * Aborts any outstanding request.
231      * @param {Number} transactionId (Optional) defaults to the last transaction
232      */
233     abort : function(transId){
234         if(transId || this.isLoading()){
235             Roo.lib.Ajax.abort(transId || this.transId);
236         }
237     },
238
239     // private
240     handleResponse : function(response){
241         this.transId = false;
242         var options = response.argument.options;
243         response.argument = options ? options.argument : null;
244         this.fireEvent("requestcomplete", this, response, options);
245         Roo.callback(options.success, options.scope, [response, options]);
246         Roo.callback(options.callback, options.scope, [options, true, response]);
247     },
248
249     // private
250     handleFailure : function(response, e){
251         this.transId = false;
252         var options = response.argument.options;
253         response.argument = options ? options.argument : null;
254         this.fireEvent("requestexception", this, response, options, e);
255         Roo.callback(options.failure, options.scope, [response, options]);
256         Roo.callback(options.callback, options.scope, [options, false, response]);
257     },
258
259     // private
260     doFormUpload : function(o, ps, url){
261         var id = Roo.id();
262         var frame = document.createElement('iframe');
263         frame.id = id;
264         frame.name = id;
265         frame.className = 'x-hidden';
266         if(Roo.isIE){
267             frame.src = Roo.SSL_SECURE_URL;
268         }
269         document.body.appendChild(frame);
270
271         if(Roo.isIE){
272            document.frames[id].name = id;
273         }
274
275         var form = Roo.getDom(o.form);
276         form.target = id;
277         form.method = 'POST';
278         form.enctype = form.encoding = 'multipart/form-data';
279         if(url){
280             form.action = url;
281         }
282
283         var hiddens, hd;
284         if(ps){ // add dynamic params
285             hiddens = [];
286             ps = Roo.urlDecode(ps, false);
287             for(var k in ps){
288                 if(ps.hasOwnProperty(k)){
289                     hd = document.createElement('input');
290                     hd.type = 'hidden';
291                     hd.name = k;
292                     hd.value = ps[k];
293                     form.appendChild(hd);
294                     hiddens.push(hd);
295                 }
296             }
297         }
298
299         function cb(){
300             var r = {  // bogus response object
301                 responseText : '',
302                 responseXML : null
303             };
304
305             r.argument = o ? o.argument : null;
306
307             try { //
308                 var doc;
309                 if(Roo.isIE){
310                     doc = frame.contentWindow.document;
311                 }else {
312                     doc = (frame.contentDocument || window.frames[id].document);
313                 }
314                 if(doc && doc.body){
315                     r.responseText = doc.body.innerHTML;
316                 }
317                 if(doc && doc.XMLDocument){
318                     r.responseXML = doc.XMLDocument;
319                 }else {
320                     r.responseXML = doc;
321                 }
322             }
323             catch(e) {
324                 // ignore
325             }
326
327             Roo.EventManager.removeListener(frame, 'load', cb, this);
328
329             this.fireEvent("requestcomplete", this, r, o);
330             Roo.callback(o.success, o.scope, [r, o]);
331             Roo.callback(o.callback, o.scope, [o, true, r]);
332
333             setTimeout(function(){document.body.removeChild(frame);}, 100);
334         }
335
336         Roo.EventManager.on(frame, 'load', cb, this);
337         form.submit();
338
339         if(hiddens){ // remove dynamic params
340             for(var i = 0, len = hiddens.length; i < len; i++){
341                 form.removeChild(hiddens[i]);
342             }
343         }
344     },
345     // this is a 'formdata version???'
346     
347     
348     doFormDataUpload : function(o, ps, url)
349     {
350         var form = Roo.getDom(o.form);
351         form.enctype = form.encoding = 'multipart/form-data';
352         var formData = o.formData === true ? new FormData(form) : o.formData;
353       
354         var cb = {
355             success: this.handleResponse,
356             failure: this.handleFailure,
357             scope: this,
358             argument: {options: o},
359             timeout : o.timeout || this.timeout
360         };
361  
362         if(typeof o.autoAbort == 'boolean'){ // options gets top priority
363             if(o.autoAbort){
364                 this.abort();
365             }
366         }else if(this.autoAbort !== false){
367             this.abort();
368         }
369
370         //Roo.lib.Ajax.defaultPostHeader = null;
371         Roo.lib.Ajax.useDefaultHeader = false;
372         this.transId = Roo.lib.Ajax.request( "POST", url, cb, o.formData, o);
373         Roo.lib.Ajax.useDefaultHeader = true;
374  
375          
376     }
377     
378 });