Fixes #1155 - Cookie requires Browser for the document object in the options. Otherwi...
[mootools/dkf.git] / Docs / Request / Request.md
blobb07c278cf1734abf458b553c15313e44b2513b8b
1 Class: Request {#Request}
2 =========================
4 An XMLHttpRequest Wrapper.
6 ### Implements:
8 [Chain][], [Events][], [Options][]
10 ### Syntax:
12         var myRequest = new Request([options]);
14 ### Arguments:
16 2. options - (*object*, optional) See below.
18 ### Options:
20 * url        - (*string*: defaults to null) The URL to request. (Note, this can also be an instance of [URI][])
21 * method     - (*string*: defaults to 'post') The HTTP method for the request, can be either 'post' or 'get'.
22 * data       - (*string*: defaults to '') The default data for [Request:send][], used when no data is given.
23 * link       - (*string*: defaults to 'ignore') Can be 'ignore', 'cancel' and 'chain'.
24         * 'ignore' - Any calls made to start while the request is running will be ignored. (Synonymous with 'wait': true from 1.11)
25         * 'cancel' - Any calls made to start while the request is running will take precedence over the currently running request. The new request will start immediately, canceling the one that is currently running. (Synonymous with 'wait': false from 1.11)
26         * 'chain'  - Any calls made to start while the request is running will be chained up, and will take place as soon as the current request has finished, one after another.
27 * async      - (*boolean*: defaults to true) If set to false, the requests will be synchronous and freeze the browser during request.
28 * encoding   - (*string*: defaults to 'utf-8') The encoding to be set in the request header.
29 * headers    - (*object*) An object to use in order to set the request headers.
30 * isSuccess  - (*function*) Overrides the built-in isSuccess function.
31 * evalScripts  - (*boolean*: defaults to false) If set to true, `script` tags inside the response will be evaluated.
32 * evalResponse - (*boolean*: defaults to false) If set to true, the entire response will be evaluated. Responses with javascript content-type will be evaluated automatically.
33 * emulation  - (*boolean*: defaults to true) If set to true, other methods than 'post' or 'get' are appended as post-data named '\_method' (used in rails)
34 * urlEncoded - (*boolean*: defaults to true) If set to true, the content-type header is set to www-form-urlencoded + encoding
35 * timeout - (*integer*: defaults to 0) In conjunction with `onTimeout` event, it determines the amount of milliseconds before considering a connection timed out. (It's suggested to not use timeout with big files and only when knowing what's expected.)
36 * noCache - (*boolean*; defaults to false) If *true*, appends a unique *noCache* value to the request to prevent caching. (IE has a bad habit of caching ajax request values. Including this script and setting the *noCache* value to true will prevent it from caching. The server should ignore the *noCache* value.)
37 * user - (*string*: defaults to undefined) When username is set the Request will open with credentials and try to authenticate.
38 * password - (*string*: defaults to undefined) You can use this option together with the `user` option to set authentication credentials when necessary. Note that the password will be passed as plain text and is therefore readable by anyone through the source code. It is therefore encouraged to use this option carefully
40 ### Events:
42 #### request
44 Fired when the Request is sent.
46 ##### Signature:
48         onRequest()
50 #### loadstart
52 Fired when the Request loaded, right before any progress starts. (This is limited to Browsers that support the event. At this time: Gecko and WebKit).
54 ##### Signature:
56         onLoadstart(event, xhr)
58 ##### Arguments:
60 1. event - (Event) The loadstart event.
61 2. xhr - (XMLHttpRequest) The transport instance.
63 #### progress
65 Fired when the Request is making progresses in the download or upload. (This is limited to Browsers that support the event. At this time: Gecko and WebKit).
67 ##### Signature:
69         onProgress(event, xhr)
71 ##### Arguments:
73 1. event - (Event) The progress event, containing currently downloaded bytes and total bytes.
74 2. xhr - (XMLHttpRequest) The transport instance.
76 ### Example:
78         var myRequest = new Request({
79                 url: 'image.jpg',
80                 onProgress: function(event, xhr) {
81                         var loaded = event.loaded, total = event.total;
83                         console.log(parseInt(loaded / total * 100, 10));
84                 }
85         });
87         myRequest.send();
89 ### See Also:
91  - [MDC: nsIDOMProgressEvent](https://developer.mozilla.org/en/XPCOM_Interface_Reference/nsIDOMProgressEvent)
93 #### complete
95 Fired when the Request is completed.
97 ##### Signature:
99         onComplete()
101 #### cancel
103 Fired when a request has been cancelled.
105 ##### Signature:
107         onCancel()
109 #### success
111 Fired when the Request is completed successfully.
113 ##### Signature:
115         onSuccess(responseText, responseXML)
117 ##### Arguments:
119 1. responseText - (*string*) The returned text from the request.
120 2. responseXML  - (*mixed*) The response XML from the request.
122 #### failure
124 Fired when the request failed (error status code).
126 ##### Signature:
128         onFailure(xhr)
130 ##### Arguments:
132 xhr - (XMLHttpRequest) The transport instance.
134 #### exception
136 Fired when setting a request header fails.
138 ##### Signature:
140         onException(headerName, value)
142 ##### Arguments:
144 1. headerName - (*string*) The name of the failing header.
145 2. value      - (*string*) The value of the failing header.
147 ### Properties:
149 * response - (*object*) Object with text and XML as keys. You can access this property in the 'success' event.
151 ### Returns:
153 * (*object*) A new Request instance.
155 ### Example:
157         var myRequest = new Request({method: 'get', url: 'requestHandler.php'});
158         myRequest.send('name=john&lastname=dorian');
160 ### See Also:
162  - [Wikipedia: XMLHttpRequest](http://en.wikipedia.org/wiki/XMLHttpRequest)
164 #### timeout
166 Fired when a request doesn't change state for `options.timeout` milliseconds.
168 ##### Signature:
170         onTimeout()
173 ### Example:
175 This example fetches some text with Request. When the user clicks the link, the returned text by the server is used to update
176 the element's text. It uses the `onRequest`, `onSuccess` and `onFailure` events to inform the user about the current state of
177 the request. The `method` option is set to `get` because we get some text instead of posting it to the server. It gets the
178 data-userid attribute of the clicked link, which will be used for the querystring.
180         var myElement = document.id('myElement');
182         var myRequest = new Request({
183                 url: 'getMyText.php',
184                 method: 'get',
185                 onRequest: function(){
186                         myElement.set('text', 'loading...');
187                 },
188                 onSuccess: function(responseText){
189                         myElement.set('text', responseText);
190                 },
191                 onFailure: function(){
192                         myElement.set('text', 'Sorry, your request failed :(');
193                 }
194         });
196         document.id('myLink').addEvent('click', function(event){
197                 event.stop();
198                 myRequest.send('userid=' + this.get('data-userid'));
199         });
203 Request Method: setHeader {#Request:setHeader}
204 --------------------------------------
206 Add or modify a header for the request. It will not override headers from the options.
208 ### Syntax:
210         myRequest.setHeader(name, value);
212 ### Arguments:
214 1. name  - (*string*) The name for the header.
215 2. value - (*string*) The value to be assigned.
217 ### Returns:
219 * (*object*) This Request instance.
221 ### Example:
223         var myRequest = new Request({url: 'getData.php', method: 'get', headers: {'X-Request': 'JSON'}});
224         myRequest.setHeader('Last-Modified','Sat, 1 Jan 2005 05:00:00 GMT');
226 Request Method: getHeader {#Request:getHeader}
227 --------------------------------------
229 Returns the given response header or null if not found.
231 ### Syntax:
233         myRequest.getHeader(name);
235 ### Arguments:
237 1. name - (*string*) The name of the header to retrieve the value of.
239 ### Returns:
241 * (*string*) The value of the retrieved header.
242 * (*null*) `null` if the header is not found.
244 ### Example:
246         var myRequest = new Request({url: 'getData.php', method: 'get', onSuccess: function(responseText, responseXML) {
247                 alert(this.getHeader('Date')); // alerts the server date (for example, 'Thu, 26 Feb 2009 20:26:06 GMT')
248         }});
250 Request Method: send {#Request:send}
251 ----------------------------
253 Opens the Request connection and sends the provided data with the specified options.
255 ### Syntax:
257         myRequest.send([options]);
259 ### Arguments:
261 1. options - (*object*, optional) The options for the sent Request.  Will also accept data as a query string for compatibility reasons.
263 ### Returns:
265 * (*object*) This Request instance.
267 ### Examples:
269         var myRequest = new Request({
270                 url: 'http://localhost/some_url'
271         }).send('save=username&name=John');
274 Request Methods: send aliases {#Request:send-aliases}
275 -----------------------------------------------------
277 MooTools provides several aliases for [Request:send][] to make it easier to use different methods.
279 These aliases are:
281 - `post()` and `POST()`
282 - `get()` and `GET()`
283 - `put()` and `PUT()`
284 - `delete()` and `DELETE()`
286 ### Syntax:
288         myRequest.post([data]);
290 ### Arguments:
292 1. data - (*string*, optional) Equivalent with the `data` option of Request.
294 ### Returns:
296 * (*object*) This Request instance.
298 ### Examples:
300         var myRequest = new Request({url: 'http://localhost/some_url'});
302         myRequest.post('save=username&name=John');
303         //...is equivalent to:
304         myRequest.send({
305                 method: 'post',
306                 data: 'save=username&name=John'
307         });
309         myRequest.get('save=username&name=John');
310         //...is equivalent to:
311         myRequest.send({
312                 method: 'get',
313                 data: 'save=username&name=John'
314         });
316 ### Note:
318 By default the emulation option is set to true, so the *put* and *delete* send methods are emulated and will actually send as *post* while the method name is sent as e.g. `_method=delete`.
322 Request Method: cancel {#Request:cancel}
323 --------------------------------
325 Cancels the currently running request, if any.
327 ### Syntax:
329         myRequest.cancel();
331 ### Returns:
333 * (*object*) This Request instance.
335 ### Example:
337         var myRequest = new Request({url: 'mypage.html', method: 'get'}).send('some=data');
338         myRequest.cancel();
340 Request Method: isRunning {#Request:isRunning}
341 --------------------------------
343 Returns true if the request is currently running
345 ### Syntax:
347         myRequest.isRunning()
349 ### Returns:
351 * (*boolean*) True if the request is running
353 ### Example:
355         var myRequest = new Request({url: 'mypage.html', method: 'get'}).send('some=data');
357         if (myRequest.isRunning()) // It runs!
360 Object: Element.Properties {#Element-Properties}
361 ==============================================
363 see [Element.Properties][]
365 Element Property: send {#Element-Properties:send}
366 -------------------------------------------------
368 ### Setter
370 Sets a default Request instance for an Element.  This is useful when handling forms.
372 #### Syntax:
374         el.set('send'[, options]);
376 #### Arguments:
378 1. options - (*object*) The Request options.
380 #### Returns:
382 * (*element*) The original element.
384 #### Example:
386         myForm.set('send', {url: 'contact.php', method: 'get'});
387         myForm.send(); //Sends the form.
389 ### Getter
391 Returns the previously set Request instance (or a new one with default options).
393 #### Syntax:
395         el.get('send');
397 #### Arguments:
399 1. property - (*string*) the Request property argument.
401 ### Returns:
403 * (*object*) The Request instance.
405 #### Example:
407         el.get('send', {method: 'get'});
408         el.send();
409         el.get('send'); // returns the Request instance.
411 Type: Element {#Element}
412 ========================
414 Custom Type to allow all of its methods to be used with any DOM element via the dollar function [$][].
417 Element Method: send {#Element:send}
418 ------------------------------------
420 Sends a form or a container of inputs with an HTML request.
422 ### Syntax:
424         myElement.send(url);
426 ### Arguments:
428 1. url - (*string*, optional) The url you want to send the form or the "container of inputs" to. If url is omitted, the action of the form will be used. url cannot be omitted for "container of inputs".
430 ### Returns:
432 * (element) This Element.
434 ### Example:
436 ##### HTML
438         <form id="myForm" action="submit.php">
439                 <p>
440                         <input name="email" value="bob@bob.com" />
441                         <input name="zipCode" value="90210" />
442                 </p>
443         </form>
445 ##### JavaScript
447         $('myForm').send();
449 ### Note:
451 * The URL is taken from the action attribute of the form.
455 [$]: /core/Element/Element/#Window:dollar
456 [Request:send]: #Request:send
457 [Element.Properties]: /core/Element/Element/#Element-Properties
458 [URI]: /more/Native/URI
459 [Chain]: /core/Class/Class.Extras#Chain
460 [Events]: /core/Class/Class.Extras#Events
461 [Options]: /core/Class/Class.Extras#Options