.travis.yml: Add Node 4, remove iojs.
[mootools.git] / Docs / Request / Request.md
blob00c231cf1658b397597fff636915f2c279b1f3fb
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 * data       - (*mixed*: defaults to '') The default data for [Request:send][], used when no data is given. Can be an Element, Object or String. If an Object is passed the [Object:toQueryString][] method will be used to convert the object to a string. If an Element is passed the [Element:toQueryString][] method will be used to convert the Element to a string.
22 * format     - (*string*: defaults to '') If passed, an additional key 'format' will be appended to 'data' with the passed value. e.g. '&format=json'
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 * method     - (*string*: defaults to 'post') The HTTP method for the request, can be either 'post' or 'get'.
28 * emulation  - (*boolean*: defaults to *true*) If set to true, other methods than 'post' or 'get' are appended as post-data named '\_method' (as used in rails)
29 * async      - (*boolean*: defaults to *true*) If set to false, the requests will be synchronous and freeze the browser during request.
30 * 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.)
31 * headers    - (*object*) An object to use in order to set the request headers.
32 * urlEncoded - (*boolean*: defaults to *true*) If set to true, the content-type header is set to www-form-urlencoded + encoding
33 * encoding   - (*string*: defaults to 'utf-8') The encoding to be set in the request header.
34 * noCache    - (*boolean*; defaults to *false*) If *true*, appends a unique *noCache* value to the request to prevent caching. (IE and iOS 6 have 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.)
35 * isSuccess  - (*function*) Overrides the built-in isSuccess function.
36 * evalScripts  - (*boolean*: defaults to *false*) If set to true, `script` tags inside the response will be evaluated.
37 * evalResponse - (*boolean*: defaults to *false*) If set to true, the entire response will be evaluated. Responses with javascript content-type will be evaluated automatically.
38 * user       - (*string*: defaults to *null*) The username to use for http basic authentication.
39 * password   - (*string*: defaults to *null*) 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 * withCredentials   - (*boolean*: defaults to *false*) If set to true, xhr.withCredentials will be set to true allowing cookies/auth to be passed for cross origin requests
42 ### Events:
44 #### request
46 Fired when the Request is sent.
48 ##### Signature:
50         onRequest()
52 #### loadstart
54 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).
56 ##### Signature:
58         onLoadstart(event, xhr)
60 ##### Arguments:
62 1. event - (Event) The loadstart event.
63 2. xhr - (XMLHttpRequest) The transport instance.
65 #### progress
67 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).
69 ##### Signature:
71         onProgress(event, xhr)
73 ##### Arguments:
75 1. event - (Event) The progress event, containing currently downloaded bytes and total bytes.
76 2. xhr - (XMLHttpRequest) The transport instance.
78 ### Example:
80         var myRequest = new Request({
81                 url: 'image.jpg',
82                 onProgress: function(event, xhr){
83                         var loaded = event.loaded, total = event.total;
85                         console.log(parseInt(loaded / total * 100, 10));
86                 }
87         });
89         myRequest.send();
91 ### Cross-Origin Resource Sharing (CORS) note:
93 The Request class will (by default) add a custom header that, if used for a cross-origin request, will have to be reported as allowed in the preflight request, in addition to any other headers you may set yourself:
95         Access-Control-Allow-Headers: X-Requested-With
97 ### See Also:
99  - [MDN: nsIDOMProgressEvent](https://developer.mozilla.org/en/XPCOM_Interface_Reference/nsIDOMProgressEvent)
101 #### complete
103 Fired when the Request is completed.
105 ##### Signature:
107         onComplete()
109 #### cancel
111 Fired when a request has been cancelled.
113 ##### Signature:
115         onCancel()
117 #### success
119 Fired when the Request is completed successfully.
121 ##### Signature:
123         onSuccess(responseText, responseXML)
125 ##### Arguments:
127 1. responseText - (*string*) The returned text from the request.
128 2. responseXML  - (*mixed*) The response XML from the request.
130 #### failure
132 Fired when the request failed (error status code).
134 ##### Signature:
136         onFailure(xhr)
138 ##### Arguments:
140 xhr - (XMLHttpRequest) The transport instance.
142 #### exception
144 Fired when setting a request header fails.
146 ##### Signature:
148         onException(headerName, value)
150 ##### Arguments:
152 1. headerName - (*string*) The name of the failing header.
153 2. value      - (*string*) The value of the failing header.
155 ### Properties:
157 * response - (*object*) Object with text and XML as keys. You can access this property in the 'success' event.
159 ### Returns:
161 * (*object*) A new Request instance.
163 ### Example:
165         var myRequest = new Request({method: 'get', url: 'requestHandler.php'});
166         myRequest.send('name=john&lastname=dorian');
168 ### See Also:
170  - [Wikipedia: XMLHttpRequest](http://en.wikipedia.org/wiki/XMLHttpRequest)
172 #### timeout
174 Fired when a request doesn't change state for `options.timeout` milliseconds.
176 ##### Signature:
178         onTimeout()
181 ### Example:
183 This example fetches some text with Request. When the user clicks the link, the returned text by the server is used to update
184 the element's text. It uses the `onRequest`, `onSuccess` and `onFailure` events to inform the user about the current state of
185 the request. The `method` option is set to `get` because we get some text instead of posting it to the server. It gets the
186 data-userid attribute of the clicked link, which will be used for the querystring.
188         var myElement = document.id('myElement');
190         var myRequest = new Request({
191                 url: 'getMyText.php',
192                 method: 'get',
193                 onRequest: function(){
194                         myElement.set('text', 'loading...');
195                 },
196                 onSuccess: function(responseText){
197                         myElement.set('text', responseText);
198                 },
199                 onFailure: function(){
200                         myElement.set('text', 'Sorry, your request failed :(');
201                 }
202         });
204         document.id('myLink').addEvent('click', function(event){
205                 event.stop();
206                 myRequest.send('userid=' + this.get('data-userid'));
207         });
211 Request Method: setHeader {#Request:setHeader}
212 --------------------------------------
214 Add or modify a header for the request. It will not override headers from the options.
216 ### Syntax:
218         myRequest.setHeader(name, value);
220 ### Arguments:
222 1. name  - (*string*) The name for the header.
223 2. value - (*string*) The value to be assigned.
225 ### Returns:
227 * (*object*) This Request instance.
229 ### Example:
231         var myRequest = new Request({url: 'getData.php', method: 'get', headers: {'X-Request': 'JSON'}});
232         myRequest.setHeader('Last-Modified', 'Sat, 1 Jan 2005 05:00:00 GMT');
234 Request Method: getHeader {#Request:getHeader}
235 --------------------------------------
237 Returns the given response header or null if not found.
239 ### Syntax:
241         myRequest.getHeader(name);
243 ### Arguments:
245 1. name - (*string*) The name of the header to retrieve the value of.
247 ### Returns:
249 * (*string*) The value of the retrieved header.
250 * (*null*) `null` if the header is not found.
252 ### Example:
254         var myRequest = new Request({url: 'getData.php', method: 'get', onSuccess: function(responseText, responseXML){
255                 alert(this.getHeader('Date')); // alerts the server date (for example, 'Thu, 26 Feb 2009 20:26:06 GMT')
256         }});
258 Request Method: send {#Request:send}
259 ----------------------------
261 Opens the Request connection and sends the provided data with the specified options.
263 ### Syntax:
265         myRequest.send([options]);
267 ### Arguments:
269 1. options - (*object*, optional) The options for the sent Request.  Will also accept data as a query string for compatibility reasons.
271 ### Returns:
273 * (*object*) This Request instance.
275 ### Examples:
277         var myRequest = new Request({
278                 url: 'http://localhost/some_url'
279         }).send('save=username&name=John');
282 Request Methods: send aliases {#Request:send-aliases}
283 -----------------------------------------------------
285 MooTools provides several aliases for [Request:send][] to make it easier to use different methods.
287 These aliases are:
289 - `post()` and `POST()`
290 - `get()` and `GET()`
291 - `put()` and `PUT()`
292 - `delete()` and `DELETE()`
293 - `patch()` and `PATCH()`
294 - `head()` and `HEAD()`
296 ### Syntax:
298         myRequest.post([data]);
300 ### Arguments:
302 1. data - (*string*, optional) Equivalent with the `data` option of Request.
304 ### Returns:
306 * (*object*) This Request instance.
308 ### Examples:
310         var myRequest = new Request({url: 'http://localhost/some_url'});
312         myRequest.post('save=username&name=John');
313         //...is equivalent to:
314         myRequest.send({
315                 method: 'post',
316                 data: 'save=username&name=John'
317         });
319         myRequest.get('save=username&name=John');
320         //...is equivalent to:
321         myRequest.send({
322                 method: 'get',
323                 data: 'save=username&name=John'
324         });
326 ### Note:
328 By default the emulation option is set to true, so the *put*, *delete* and *patch* send methods are emulated and will actually send as *post* while the method name is sent as e.g. `_method=delete`.
330 `Async` and `timeout` options are mutually exclusive. If you set `async` to `false`, then there's no need to set the `timeout` since the server and browser will set their own timeouts to return executing the rest of your script.
333 Request Method: cancel {#Request:cancel}
334 --------------------------------
336 Cancels the currently running request, if any.
338 ### Syntax:
340         myRequest.cancel();
342 ### Returns:
344 * (*object*) This Request instance.
346 ### Example:
348         var myRequest = new Request({url: 'mypage.html', method: 'get'}).send('some=data');
349         myRequest.cancel();
351 Request Method: isRunning {#Request:isRunning}
352 --------------------------------
354 Returns true if the request is currently running
356 ### Syntax:
358         myRequest.isRunning()
360 ### Returns:
362 * (*boolean*) True if the request is running
364 ### Example:
366         var myRequest = new Request({url: 'mypage.html', method: 'get'}).send('some=data');
368         if (myRequest.isRunning()) // It runs!
371 Object: Element.Properties {#Element-Properties}
372 ==============================================
374 see [Element.Properties][]
376 Element Property: send {#Element-Properties:send}
377 -------------------------------------------------
379 ### Setter
381 Sets a default Request instance for an Element.  This is useful when handling forms.
383 #### Syntax:
385         el.set('send'[, options]);
387 #### Arguments:
389 1. options - (*object*) The Request options.
391 #### Returns:
393 * (*element*) The original element.
395 #### Example:
397         myForm.set('send', {url: 'contact.php', method: 'get'});
398         myForm.send(); //Sends the form.
400 ### Getter
402 Returns the previously set Request instance (or a new one with default options).
404 #### Syntax:
406         el.get('send');
408 #### Arguments:
410 1. property - (*string*) the Request property argument.
412 ### Returns:
414 * (*object*) The Request instance.
416 #### Example:
418         el.set('send', {method: 'get'});
419         el.send();
420         el.get('send'); // returns the Request instance.
422 Type: Element {#Element}
423 ========================
425 Custom Type to allow all of its methods to be used with any DOM element via the dollar function [$][].
428 Element Method: send {#Element:send}
429 ------------------------------------
431 Sends a form or a container of inputs with an HTML request.
433 ### Syntax:
435         myElement.send(url);
437 ### Arguments:
439 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".
441 ### Returns:
443 * (element) This Element.
445 ### Example:
447 ##### HTML
449         <form id="myForm" action="submit.php">
450                 <p>
451                         <input name="email" value="bob@bob.com" />
452                         <input name="zipCode" value="90210" />
453                 </p>
454         </form>
456 ##### JavaScript
458         $('myForm').send();
460 ### Note:
462 * The URL is taken from the action attribute of the form.
466 [$]: /core/Element/Element/#Window:dollar
467 [Request:send]: #Request:send
468 [Element.Properties]: /core/Element/Element/#Element-Properties
469 [URI]: /more/Types/URI
470 [Chain]: /core/Class/Class.Extras#Chain
471 [Events]: /core/Class/Class.Extras#Events
472 [Options]: /core/Class/Class.Extras#Options
473 [Object:toQueryString]: /core/Types/Object#Object:Object-toQueryString
474 [Element:toQueryString]: /core/Element/Element#Element:toQueryString