Upgrade to ExtJS 3.2.2 - Released 06/02/2010
[extjs.git] / src / ext-core / src / data / Connection.js
1 /*!
2  * Ext JS Library 3.2.2
3  * Copyright(c) 2006-2010 Ext JS, Inc.
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 (function(){
8     var BEFOREREQUEST = "beforerequest",
9         REQUESTCOMPLETE = "requestcomplete",
10         REQUESTEXCEPTION = "requestexception",
11         UNDEFINED = undefined,
12         LOAD = 'load',
13         POST = 'POST',
14         GET = 'GET',
15         WINDOW = window;
16
17     /**
18      * @class Ext.data.Connection
19      * @extends Ext.util.Observable
20      * <p>The class encapsulates a connection to the page's originating domain, allowing requests to be made
21      * either to a configured URL, or to a URL specified at request time.</p>
22      * <p>Requests made by this class are asynchronous, and will return immediately. No data from
23      * the server will be available to the statement immediately following the {@link #request} call.
24      * To process returned data, use a
25      * <a href="#request-option-success" ext:member="request-option-success" ext:cls="Ext.data.Connection">success callback</a>
26      * in the request options object,
27      * or an {@link #requestcomplete event listener}.</p>
28      * <p><h3>File Uploads</h3><a href="#request-option-isUpload" ext:member="request-option-isUpload" ext:cls="Ext.data.Connection">File uploads</a> are not performed using normal "Ajax" techniques, that
29      * is they are <b>not</b> performed using XMLHttpRequests. Instead the form is submitted in the standard
30      * manner with the DOM <tt>&lt;form></tt> element temporarily modified to have its
31      * <a href="http://www.w3.org/TR/REC-html40/present/frames.html#adef-target">target</a> set to refer
32      * to a dynamically generated, hidden <tt>&lt;iframe></tt> which is inserted into the document
33      * but removed after the return data has been gathered.</p>
34      * <p>The server response is parsed by the browser to create the document for the IFRAME. If the
35      * server is using JSON to send the return object, then the
36      * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17">Content-Type</a> header
37      * must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.</p>
38      * <p>Characters which are significant to an HTML parser must be sent as HTML entities, so encode
39      * "&lt;" as "&amp;lt;", "&amp;" as "&amp;amp;" etc.</p>
40      * <p>The response text is retrieved from the document, and a fake XMLHttpRequest object
41      * is created containing a <tt>responseText</tt> property in order to conform to the
42      * requirements of event handlers and callbacks.</p>
43      * <p>Be aware that file upload packets are sent with the content type <a href="http://www.faqs.org/rfcs/rfc2388.html">multipart/form</a>
44      * and some server technologies (notably JEE) may require some custom processing in order to
45      * retrieve parameter names and parameter values from the packet content.</p>
46      * <p>Also note that it's not possible to check the response code of the hidden iframe, so the success handler will ALWAYS fire.</p>
47      * @constructor
48      * @param {Object} config a configuration object.
49      */
50     Ext.data.Connection = function(config){
51         Ext.apply(this, config);
52         this.addEvents(
53             /**
54              * @event beforerequest
55              * Fires before a network request is made to retrieve a data object.
56              * @param {Connection} conn This Connection object.
57              * @param {Object} options The options config object passed to the {@link #request} method.
58              */
59             BEFOREREQUEST,
60             /**
61              * @event requestcomplete
62              * Fires if the request was successfully completed.
63              * @param {Connection} conn This Connection object.
64              * @param {Object} response The XHR object containing the response data.
65              * See <a href="http://www.w3.org/TR/XMLHttpRequest/">The XMLHttpRequest Object</a>
66              * for details.
67              * @param {Object} options The options config object passed to the {@link #request} method.
68              */
69             REQUESTCOMPLETE,
70             /**
71              * @event requestexception
72              * Fires if an error HTTP status was returned from the server.
73              * See <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">HTTP Status Code Definitions</a>
74              * for details of HTTP status codes.
75              * @param {Connection} conn This Connection object.
76              * @param {Object} response The XHR object containing the response data.
77              * See <a href="http://www.w3.org/TR/XMLHttpRequest/">The XMLHttpRequest Object</a>
78              * for details.
79              * @param {Object} options The options config object passed to the {@link #request} method.
80              */
81             REQUESTEXCEPTION
82         );
83         Ext.data.Connection.superclass.constructor.call(this);
84     };
85
86     Ext.extend(Ext.data.Connection, Ext.util.Observable, {
87         /**
88          * @cfg {String} url (Optional) <p>The default URL to be used for requests to the server. Defaults to undefined.</p>
89          * <p>The <code>url</code> config may be a function which <i>returns</i> the URL to use for the Ajax request. The scope
90          * (<code><b>this</b></code> reference) of the function is the <code>scope</code> option passed to the {@link #request} method.</p>
91          */
92         /**
93          * @cfg {Object} extraParams (Optional) An object containing properties which are used as
94          * extra parameters to each request made by this object. (defaults to undefined)
95          */
96         /**
97          * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
98          *  to each request made by this object. (defaults to undefined)
99          */
100         /**
101          * @cfg {String} method (Optional) The default HTTP method to be used for requests.
102          * (defaults to undefined; if not set, but {@link #request} params are present, POST will be used;
103          * otherwise, GET will be used.)
104          */
105         /**
106          * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
107          */
108         timeout : 30000,
109         /**
110          * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
111          * @type Boolean
112          */
113         autoAbort:false,
114
115         /**
116          * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
117          * @type Boolean
118          */
119         disableCaching: true,
120
121         /**
122          * @cfg {String} disableCachingParam (Optional) Change the parameter which is sent went disabling caching
123          * through a cache buster. Defaults to '_dc'
124          * @type String
125          */
126         disableCachingParam: '_dc',
127
128         /**
129          * <p>Sends an HTTP request to a remote server.</p>
130          * <p><b>Important:</b> Ajax server requests are asynchronous, and this call will
131          * return before the response has been received. Process any returned data
132          * in a callback function.</p>
133          * <pre><code>
134 Ext.Ajax.request({
135    url: 'ajax_demo/sample.json',
136    success: function(response, opts) {
137       var obj = Ext.decode(response.responseText);
138       console.dir(obj);
139    },
140    failure: function(response, opts) {
141       console.log('server-side failure with status code ' + response.status);
142    }
143 });
144          * </code></pre>
145          * <p>To execute a callback function in the correct scope, use the <tt>scope</tt> option.</p>
146          * @param {Object} options An object which may contain the following properties:<ul>
147          * <li><b>url</b> : String/Function (Optional)<div class="sub-desc">The URL to
148          * which to send the request, or a function to call which returns a URL string. The scope of the
149          * function is specified by the <tt>scope</tt> option. Defaults to the configured
150          * <tt>{@link #url}</tt>.</div></li>
151          * <li><b>params</b> : Object/String/Function (Optional)<div class="sub-desc">
152          * An object containing properties which are used as parameters to the
153          * request, a url encoded string or a function to call to get either. The scope of the function
154          * is specified by the <tt>scope</tt> option.</div></li>
155          * <li><b>method</b> : String (Optional)<div class="sub-desc">The HTTP method to use
156          * for the request. Defaults to the configured method, or if no method was configured,
157          * "GET" if no parameters are being sent, and "POST" if parameters are being sent.  Note that
158          * the method name is case-sensitive and should be all caps.</div></li>
159          * <li><b>callback</b> : Function (Optional)<div class="sub-desc">The
160          * function to be called upon receipt of the HTTP response. The callback is
161          * called regardless of success or failure and is passed the following
162          * parameters:<ul>
163          * <li><b>options</b> : Object<div class="sub-desc">The parameter to the request call.</div></li>
164          * <li><b>success</b> : Boolean<div class="sub-desc">True if the request succeeded.</div></li>
165          * <li><b>response</b> : Object<div class="sub-desc">The XMLHttpRequest object containing the response data.
166          * See <a href="http://www.w3.org/TR/XMLHttpRequest/">http://www.w3.org/TR/XMLHttpRequest/</a> for details about
167          * accessing elements of the response.</div></li>
168          * </ul></div></li>
169          * <li><a id="request-option-success"></a><b>success</b> : Function (Optional)<div class="sub-desc">The function
170          * to be called upon success of the request. The callback is passed the following
171          * parameters:<ul>
172          * <li><b>response</b> : Object<div class="sub-desc">The XMLHttpRequest object containing the response data.</div></li>
173          * <li><b>options</b> : Object<div class="sub-desc">The parameter to the request call.</div></li>
174          * </ul></div></li>
175          * <li><b>failure</b> : Function (Optional)<div class="sub-desc">The function
176          * to be called upon failure of the request. The callback is passed the
177          * following parameters:<ul>
178          * <li><b>response</b> : Object<div class="sub-desc">The XMLHttpRequest object containing the response data.</div></li>
179          * <li><b>options</b> : Object<div class="sub-desc">The parameter to the request call.</div></li>
180          * </ul></div></li>
181          * <li><b>scope</b> : Object (Optional)<div class="sub-desc">The scope in
182          * which to execute the callbacks: The "this" object for the callback function. If the <tt>url</tt>, or <tt>params</tt> options were
183          * specified as functions from which to draw values, then this also serves as the scope for those function calls.
184          * Defaults to the browser window.</div></li>
185          * <li><b>timeout</b> : Number (Optional)<div class="sub-desc">The timeout in milliseconds to be used for this request. Defaults to 30 seconds.</div></li>
186          * <li><b>form</b> : Element/HTMLElement/String (Optional)<div class="sub-desc">The <tt>&lt;form&gt;</tt>
187          * Element or the id of the <tt>&lt;form&gt;</tt> to pull parameters from.</div></li>
188          * <li><a id="request-option-isUpload"></a><b>isUpload</b> : Boolean (Optional)<div class="sub-desc"><b>Only meaningful when used
189          * with the <tt>form</tt> option</b>.
190          * <p>True if the form object is a file upload (will be set automatically if the form was
191          * configured with <b><tt>enctype</tt></b> "multipart/form-data").</p>
192          * <p>File uploads are not performed using normal "Ajax" techniques, that is they are <b>not</b>
193          * performed using XMLHttpRequests. Instead the form is submitted in the standard manner with the
194          * DOM <tt>&lt;form></tt> element temporarily modified to have its
195          * <a href="http://www.w3.org/TR/REC-html40/present/frames.html#adef-target">target</a> set to refer
196          * to a dynamically generated, hidden <tt>&lt;iframe></tt> which is inserted into the document
197          * but removed after the return data has been gathered.</p>
198          * <p>The server response is parsed by the browser to create the document for the IFRAME. If the
199          * server is using JSON to send the return object, then the
200          * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17">Content-Type</a> header
201          * must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.</p>
202          * <p>The response text is retrieved from the document, and a fake XMLHttpRequest object
203          * is created containing a <tt>responseText</tt> property in order to conform to the
204          * requirements of event handlers and callbacks.</p>
205          * <p>Be aware that file upload packets are sent with the content type <a href="http://www.faqs.org/rfcs/rfc2388.html">multipart/form</a>
206          * and some server technologies (notably JEE) may require some custom processing in order to
207          * retrieve parameter names and parameter values from the packet content.</p>
208          * </div></li>
209          * <li><b>headers</b> : Object (Optional)<div class="sub-desc">Request
210          * headers to set for the request.</div></li>
211          * <li><b>xmlData</b> : Object (Optional)<div class="sub-desc">XML document
212          * to use for the post. Note: This will be used instead of params for the post
213          * data. Any params will be appended to the URL.</div></li>
214          * <li><b>jsonData</b> : Object/String (Optional)<div class="sub-desc">JSON
215          * data to use as the post. Note: This will be used instead of params for the post
216          * data. Any params will be appended to the URL.</div></li>
217          * <li><b>disableCaching</b> : Boolean (Optional)<div class="sub-desc">True
218          * to add a unique cache-buster param to GET requests.</div></li>
219          * </ul></p>
220          * <p>The options object may also contain any other property which might be needed to perform
221          * postprocessing in a callback because it is passed to callback functions.</p>
222          * @return {Number} transactionId The id of the server transaction. This may be used
223          * to cancel the request.
224          */
225         request : function(o){
226             var me = this;
227             if(me.fireEvent(BEFOREREQUEST, me, o)){
228                 if (o.el) {
229                     if(!Ext.isEmpty(o.indicatorText)){
230                         me.indicatorText = '<div class="loading-indicator">'+o.indicatorText+"</div>";
231                     }
232                     if(me.indicatorText) {
233                         Ext.getDom(o.el).innerHTML = me.indicatorText;
234                     }
235                     o.success = (Ext.isFunction(o.success) ? o.success : function(){}).createInterceptor(function(response) {
236                         Ext.getDom(o.el).innerHTML = response.responseText;
237                     });
238                 }
239
240                 var p = o.params,
241                     url = o.url || me.url,
242                     method,
243                     cb = {success: me.handleResponse,
244                           failure: me.handleFailure,
245                           scope: me,
246                           argument: {options: o},
247                           timeout : o.timeout || me.timeout
248                     },
249                     form,
250                     serForm;
251
252
253                 if (Ext.isFunction(p)) {
254                     p = p.call(o.scope||WINDOW, o);
255                 }
256
257                 p = Ext.urlEncode(me.extraParams, Ext.isObject(p) ? Ext.urlEncode(p) : p);
258
259                 if (Ext.isFunction(url)) {
260                     url = url.call(o.scope || WINDOW, o);
261                 }
262
263                 if((form = Ext.getDom(o.form))){
264                     url = url || form.action;
265                      if(o.isUpload || /multipart\/form-data/i.test(form.getAttribute("enctype"))) {
266                          return me.doFormUpload.call(me, o, p, url);
267                      }
268                     serForm = Ext.lib.Ajax.serializeForm(form);
269                     p = p ? (p + '&' + serForm) : serForm;
270                 }
271
272                 method = o.method || me.method || ((p || o.xmlData || o.jsonData) ? POST : GET);
273
274                 if(method === GET && (me.disableCaching && o.disableCaching !== false) || o.disableCaching === true){
275                     var dcp = o.disableCachingParam || me.disableCachingParam;
276                     url = Ext.urlAppend(url, dcp + '=' + (new Date().getTime()));
277                 }
278
279                 o.headers = Ext.apply(o.headers || {}, me.defaultHeaders || {});
280
281                 if(o.autoAbort === true || me.autoAbort) {
282                     me.abort();
283                 }
284
285                 if((method == GET || o.xmlData || o.jsonData) && p){
286                     url = Ext.urlAppend(url, p);
287                     p = '';
288                 }
289                 return (me.transId = Ext.lib.Ajax.request(method, url, cb, p, o));
290             }else{
291                 return o.callback ? o.callback.apply(o.scope, [o,UNDEFINED,UNDEFINED]) : null;
292             }
293         },
294
295         /**
296          * Determine whether this object has a request outstanding.
297          * @param {Number} transactionId (Optional) defaults to the last transaction
298          * @return {Boolean} True if there is an outstanding request.
299          */
300         isLoading : function(transId){
301             return transId ? Ext.lib.Ajax.isCallInProgress(transId) : !! this.transId;
302         },
303
304         /**
305          * Aborts any outstanding request.
306          * @param {Number} transactionId (Optional) defaults to the last transaction
307          */
308         abort : function(transId){
309             if(transId || this.isLoading()){
310                 Ext.lib.Ajax.abort(transId || this.transId);
311             }
312         },
313
314         // private
315         handleResponse : function(response){
316             this.transId = false;
317             var options = response.argument.options;
318             response.argument = options ? options.argument : null;
319             this.fireEvent(REQUESTCOMPLETE, this, response, options);
320             if(options.success){
321                 options.success.call(options.scope, response, options);
322             }
323             if(options.callback){
324                 options.callback.call(options.scope, options, true, response);
325             }
326         },
327
328         // private
329         handleFailure : function(response, e){
330             this.transId = false;
331             var options = response.argument.options;
332             response.argument = options ? options.argument : null;
333             this.fireEvent(REQUESTEXCEPTION, this, response, options, e);
334             if(options.failure){
335                 options.failure.call(options.scope, response, options);
336             }
337             if(options.callback){
338                 options.callback.call(options.scope, options, false, response);
339             }
340         },
341
342         // private
343         doFormUpload : function(o, ps, url){
344             var id = Ext.id(),
345                 doc = document,
346                 frame = doc.createElement('iframe'),
347                 form = Ext.getDom(o.form),
348                 hiddens = [],
349                 hd,
350                 encoding = 'multipart/form-data',
351                 buf = {
352                     target: form.target,
353                     method: form.method,
354                     encoding: form.encoding,
355                     enctype: form.enctype,
356                     action: form.action
357                 };
358
359             /*
360              * Originally this behaviour was modified for Opera 10 to apply the secure URL after
361              * the frame had been added to the document. It seems this has since been corrected in
362              * Opera so the behaviour has been reverted, the URL will be set before being added.
363              */
364             Ext.fly(frame).set({
365                 id: id,
366                 name: id,
367                 cls: 'x-hidden',
368                 src: Ext.SSL_SECURE_URL
369             }); 
370
371             doc.body.appendChild(frame);
372
373             // This is required so that IE doesn't pop the response up in a new window.
374             if(Ext.isIE){
375                document.frames[id].name = id;
376             }
377
378
379             Ext.fly(form).set({
380                 target: id,
381                 method: POST,
382                 enctype: encoding,
383                 encoding: encoding,
384                 action: url || buf.action
385             });
386
387             // add dynamic params
388             Ext.iterate(Ext.urlDecode(ps, false), function(k, v){
389                 hd = doc.createElement('input');
390                 Ext.fly(hd).set({
391                     type: 'hidden',
392                     value: v,
393                     name: k
394                 });
395                 form.appendChild(hd);
396                 hiddens.push(hd);
397             });
398
399             function cb(){
400                 var me = this,
401                     // bogus response object
402                     r = {responseText : '',
403                          responseXML : null,
404                          argument : o.argument},
405                     doc,
406                     firstChild;
407
408                 try{
409                     doc = frame.contentWindow.document || frame.contentDocument || WINDOW.frames[id].document;
410                     if(doc){
411                         if(doc.body){
412                             if(/textarea/i.test((firstChild = doc.body.firstChild || {}).tagName)){ // json response wrapped in textarea
413                                 r.responseText = firstChild.value;
414                             }else{
415                                 r.responseText = doc.body.innerHTML;
416                             }
417                         }
418                         //in IE the document may still have a body even if returns XML.
419                         r.responseXML = doc.XMLDocument || doc;
420                     }
421                 }
422                 catch(e) {}
423
424                 Ext.EventManager.removeListener(frame, LOAD, cb, me);
425
426                 me.fireEvent(REQUESTCOMPLETE, me, r, o);
427
428                 function runCallback(fn, scope, args){
429                     if(Ext.isFunction(fn)){
430                         fn.apply(scope, args);
431                     }
432                 }
433
434                 runCallback(o.success, o.scope, [r, o]);
435                 runCallback(o.callback, o.scope, [o, true, r]);
436
437                 if(!me.debugUploads){
438                     setTimeout(function(){Ext.removeNode(frame);}, 100);
439                 }
440             }
441
442             Ext.EventManager.on(frame, LOAD, cb, this);
443             form.submit();
444
445             Ext.fly(form).set(buf);
446             Ext.each(hiddens, function(h) {
447                 Ext.removeNode(h);
448             });
449         }
450     });
451 })();
452
453 /**
454  * @class Ext.Ajax
455  * @extends Ext.data.Connection
456  * <p>The global Ajax request class that provides a simple way to make Ajax requests
457  * with maximum flexibility.</p>
458  * <p>Since Ext.Ajax is a singleton, you can set common properties/events for it once
459  * and override them at the request function level only if necessary.</p>
460  * <p>Common <b>Properties</b> you may want to set are:<div class="mdetail-params"><ul>
461  * <li><b><tt>{@link #method}</tt></b><p class="sub-desc"></p></li>
462  * <li><b><tt>{@link #extraParams}</tt></b><p class="sub-desc"></p></li>
463  * <li><b><tt>{@link #url}</tt></b><p class="sub-desc"></p></li>
464  * </ul></div>
465  * <pre><code>
466 // Default headers to pass in every request
467 Ext.Ajax.defaultHeaders = {
468     'Powered-By': 'Ext'
469 };
470  * </code></pre>
471  * </p>
472  * <p>Common <b>Events</b> you may want to set are:<div class="mdetail-params"><ul>
473  * <li><b><tt>{@link Ext.data.Connection#beforerequest beforerequest}</tt></b><p class="sub-desc"></p></li>
474  * <li><b><tt>{@link Ext.data.Connection#requestcomplete requestcomplete}</tt></b><p class="sub-desc"></p></li>
475  * <li><b><tt>{@link Ext.data.Connection#requestexception requestexception}</tt></b><p class="sub-desc"></p></li>
476  * </ul></div>
477  * <pre><code>
478 // Example: show a spinner during all Ajax requests
479 Ext.Ajax.on('beforerequest', this.showSpinner, this);
480 Ext.Ajax.on('requestcomplete', this.hideSpinner, this);
481 Ext.Ajax.on('requestexception', this.hideSpinner, this);
482  * </code></pre>
483  * </p>
484  * <p>An example request:</p>
485  * <pre><code>
486 // Basic request
487 Ext.Ajax.{@link Ext.data.Connection#request request}({
488    url: 'foo.php',
489    success: someFn,
490    failure: otherFn,
491    headers: {
492        'my-header': 'foo'
493    },
494    params: { foo: 'bar' }
495 });
496
497 // Simple ajax form submission
498 Ext.Ajax.{@link Ext.data.Connection#request request}({
499     form: 'some-form',
500     params: 'foo=bar'
501 });
502  * </code></pre>
503  * </p>
504  * @singleton
505  */
506 Ext.Ajax = new Ext.data.Connection({
507     /**
508      * @cfg {String} url @hide
509      */
510     /**
511      * @cfg {Object} extraParams @hide
512      */
513     /**
514      * @cfg {Object} defaultHeaders @hide
515      */
516     /**
517      * @cfg {String} method (Optional) @hide
518      */
519     /**
520      * @cfg {Number} timeout (Optional) @hide
521      */
522     /**
523      * @cfg {Boolean} autoAbort (Optional) @hide
524      */
525
526     /**
527      * @cfg {Boolean} disableCaching (Optional) @hide
528      */
529
530     /**
531      * @property  disableCaching
532      * True to add a unique cache-buster param to GET requests. (defaults to true)
533      * @type Boolean
534      */
535     /**
536      * @property  url
537      * The default URL to be used for requests to the server. (defaults to undefined)
538      * If the server receives all requests through one URL, setting this once is easier than
539      * entering it on every request.
540      * @type String
541      */
542     /**
543      * @property  extraParams
544      * An object containing properties which are used as extra parameters to each request made
545      * by this object (defaults to undefined). Session information and other data that you need
546      * to pass with each request are commonly put here.
547      * @type Object
548      */
549     /**
550      * @property  defaultHeaders
551      * An object containing request headers which are added to each request made by this object
552      * (defaults to undefined).
553      * @type Object
554      */
555     /**
556      * @property  method
557      * The default HTTP method to be used for requests. Note that this is case-sensitive and
558      * should be all caps (defaults to undefined; if not set but params are present will use
559      * <tt>"POST"</tt>, otherwise will use <tt>"GET"</tt>.)
560      * @type String
561      */
562     /**
563      * @property  timeout
564      * The timeout in milliseconds to be used for requests. (defaults to 30000)
565      * @type Number
566      */
567
568     /**
569      * @property  autoAbort
570      * Whether a new request should abort any pending requests. (defaults to false)
571      * @type Boolean
572      */
573     autoAbort : false,
574
575     /**
576      * Serialize the passed form into a url encoded string
577      * @param {String/HTMLElement} form
578      * @return {String}
579      */
580     serializeForm : function(form){
581         return Ext.lib.Ajax.serializeForm(form);
582     }
583 });