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