1 Class: Request {#Request}
2 =========================
4 An XMLHttpRequest Wrapper.
8 [Chain][], [Class.Thenable][], [Events][], [Options][]
12 var myRequest = new Request([options]);
16 2. options - (*object*, optional) See below.
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. [Take care][resetThenable-note] when using "chain" in combination with Request's thenable properties.
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
44 Request implements `Class.Thenable` to make a Request instance "thenable", i.e. `myRequest.send().then(function(response){ console.log(response.text); });`. See [Class.Thenable][] for more information.
50 Fired when the Request is sent.
58 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).
62 onLoadstart(event, xhr)
66 1. event - (Event) The loadstart event.
67 2. xhr - (XMLHttpRequest) The transport instance.
71 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).
75 onProgress(event, xhr)
79 1. event - (Event) The progress event, containing currently downloaded bytes and total bytes.
80 2. xhr - (XMLHttpRequest) The transport instance.
84 var myRequest = new Request({
86 onProgress: function(event, xhr){
87 var loaded = event.loaded, total = event.total;
89 console.log(parseInt(loaded / total * 100, 10));
95 ### Cross-Origin Resource Sharing (CORS) note:
97 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:
99 Access-Control-Allow-Headers: X-Requested-With
103 - [MDN: nsIDOMProgressEvent](https://developer.mozilla.org/en/XPCOM_Interface_Reference/nsIDOMProgressEvent)
107 Fired when the Request is completed.
115 Fired when a request has been cancelled.
123 Fired when the Request is completed successfully.
127 onSuccess(responseText, responseXML)
131 1. responseText - (*string*) The returned text from the request.
132 2. responseXML - (*mixed*) The response XML from the request.
136 Fired when the request failed (error status code).
144 xhr - (XMLHttpRequest) The transport instance.
148 Fired when setting a request header fails.
152 onException(headerName, value)
156 1. headerName - (*string*) The name of the failing header.
157 2. value - (*string*) The value of the failing header.
161 * response - (*object*) Object with text and XML as keys. You can access this property in the 'success' event.
165 * (*object*) A new Request instance.
169 var myRequest = new Request({method: 'get', url: 'requestHandler.php'});
170 myRequest.send('name=john&lastname=dorian');
174 - [Wikipedia: XMLHttpRequest](http://en.wikipedia.org/wiki/XMLHttpRequest)
178 Fired when a request doesn't change state for `options.timeout` milliseconds.
187 This example fetches some text with Request. When the user clicks the link, the returned text by the server is used to update
188 the element's text. It uses the `onRequest`, `onSuccess` and `onFailure` events to inform the user about the current state of
189 the request. The `method` option is set to `get` because we get some text instead of posting it to the server. It gets the
190 data-userid attribute of the clicked link, which will be used for the querystring.
192 var myElement = document.id('myElement');
194 var myRequest = new Request({
195 url: 'getMyText.php',
197 onRequest: function(){
198 myElement.set('text', 'loading...');
200 onSuccess: function(responseText){
201 myElement.set('text', responseText);
203 onFailure: function(){
204 myElement.set('text', 'Sorry, your request failed :(');
208 document.id('myLink').addEvent('click', function(event){
210 myRequest.send('userid=' + this.get('data-userid'));
215 Request Method: setHeader {#Request:setHeader}
216 --------------------------------------
218 Add or modify a header for the request. It will not override headers from the options.
222 myRequest.setHeader(name, value);
226 1. name - (*string*) The name for the header.
227 2. value - (*string*) The value to be assigned.
231 * (*object*) This Request instance.
235 var myRequest = new Request({url: 'getData.php', method: 'get', headers: {'X-Request': 'JSON'}});
236 myRequest.setHeader('Last-Modified', 'Sat, 1 Jan 2005 05:00:00 GMT');
238 Request Method: getHeader {#Request:getHeader}
239 --------------------------------------
241 Returns the given response header or null if not found.
245 myRequest.getHeader(name);
249 1. name - (*string*) The name of the header to retrieve the value of.
253 * (*string*) The value of the retrieved header.
254 * (*null*) `null` if the header is not found.
258 var myRequest = new Request({url: 'getData.php', method: 'get', onSuccess: function(responseText, responseXML){
259 alert(this.getHeader('Date')); // alerts the server date (for example, 'Thu, 26 Feb 2009 20:26:06 GMT')
262 Request Method: send {#Request:send}
263 ----------------------------
265 Opens the Request connection and sends the provided data with the specified options.
269 myRequest.send([options]);
273 1. options - (*object*, optional) The options for the sent Request. Will also accept data as a query string for compatibility reasons.
277 * (*object*) This Request instance.
281 var myRequest = new Request({
282 url: 'http://localhost/some_url'
283 }).send('save=username&name=John');
286 Request Methods: send aliases {#Request:send-aliases}
287 -----------------------------------------------------
289 MooTools provides several aliases for [Request:send][] to make it easier to use different methods.
293 - `post()` and `POST()`
294 - `get()` and `GET()`
295 - `put()` and `PUT()`
296 - `delete()` and `DELETE()`
297 - `patch()` and `PATCH()`
298 - `head()` and `HEAD()`
302 myRequest.post([data]);
306 1. data - (*string*, optional) Equivalent with the `data` option of Request.
310 * (*object*) This Request instance.
314 var myRequest = new Request({url: 'http://localhost/some_url'});
316 myRequest.post('save=username&name=John');
317 //...is equivalent to:
320 data: 'save=username&name=John'
323 myRequest.get('save=username&name=John');
324 //...is equivalent to:
327 data: 'save=username&name=John'
332 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`.
334 `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.
337 Request Method: cancel {#Request:cancel}
338 --------------------------------
340 Cancels the currently running request, if any.
348 * (*object*) This Request instance.
352 var myRequest = new Request({url: 'mypage.html', method: 'get'}).send('some=data');
355 Request Method: isRunning {#Request:isRunning}
356 --------------------------------
358 Returns true if the request is currently running
362 myRequest.isRunning()
366 * (*boolean*) True if the request is running
370 var myRequest = new Request({url: 'mypage.html', method: 'get'}).send('some=data');
372 if (myRequest.isRunning()) // It runs!
375 Object: Element.Properties {#Element-Properties}
376 ==============================================
378 see [Element.Properties][]
380 Element Property: send {#Element-Properties:send}
381 -------------------------------------------------
385 Sets a default Request instance for an Element. This is useful when handling forms.
389 el.set('send'[, options]);
393 1. options - (*object*) The Request options.
397 * (*element*) The original element.
401 myForm.set('send', {url: 'contact.php', method: 'get'});
402 myForm.send(); //Sends the form.
406 Returns the previously set Request instance (or a new one with default options).
414 1. property - (*string*) the Request property argument.
418 * (*object*) The Request instance.
422 el.set('send', {method: 'get'});
424 el.get('send'); // returns the Request instance.
426 Type: Element {#Element}
427 ========================
429 Custom Type to allow all of its methods to be used with any DOM element via the dollar function [$][].
432 Element Method: send {#Element:send}
433 ------------------------------------
435 Sends a form or a container of inputs with an HTML request.
443 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".
447 * (element) This Element.
453 <form id="myForm" action="submit.php">
455 <input name="email" value="bob@bob.com" />
456 <input name="zipCode" value="90210" />
466 * The URL is taken from the action attribute of the form.
470 [$]: /core/Element/Element/#Window:dollar
471 [Request:send]: #Request:send
472 [Element.Properties]: /core/Element/Element/#Element-Properties
473 [URI]: /more/Types/URI
474 [Chain]: /core/Class/Class.Extras#Chain
475 [Class.Thenable]: /core/Class/Class.Thenable
476 [Events]: /core/Class/Class.Extras#Events
477 [Options]: /core/Class/Class.Extras#Options
478 [Object:toQueryString]: /core/Types/Object#Object:Object-toQueryString
479 [Element:toQueryString]: /core/Element/Element#Element:toQueryString
480 [resetThenable-note]: /core/Class/Class.Thenable#Class.Thenable:resetThenable-note