1 Class: Request {#Request}
2 =========================
4 An XMLHttpRequest Wrapper.
8 [Chain][], [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.
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
46 Fired when the Request is sent.
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).
58 onLoadstart(event, xhr)
62 1. event - (Event) The loadstart event.
63 2. xhr - (XMLHttpRequest) The transport instance.
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).
71 onProgress(event, xhr)
75 1. event - (Event) The progress event, containing currently downloaded bytes and total bytes.
76 2. xhr - (XMLHttpRequest) The transport instance.
80 var myRequest = new Request({
82 onProgress: function(event, xhr){
83 var loaded = event.loaded, total = event.total;
85 console.log(parseInt(loaded / total * 100, 10));
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
99 - [MDN: nsIDOMProgressEvent](https://developer.mozilla.org/en/XPCOM_Interface_Reference/nsIDOMProgressEvent)
103 Fired when the Request is completed.
111 Fired when a request has been cancelled.
119 Fired when the Request is completed successfully.
123 onSuccess(responseText, responseXML)
127 1. responseText - (*string*) The returned text from the request.
128 2. responseXML - (*mixed*) The response XML from the request.
132 Fired when the request failed (error status code).
140 xhr - (XMLHttpRequest) The transport instance.
144 Fired when setting a request header fails.
148 onException(headerName, value)
152 1. headerName - (*string*) The name of the failing header.
153 2. value - (*string*) The value of the failing header.
157 * response - (*object*) Object with text and XML as keys. You can access this property in the 'success' event.
161 * (*object*) A new Request instance.
165 var myRequest = new Request({method: 'get', url: 'requestHandler.php'});
166 myRequest.send('name=john&lastname=dorian');
170 - [Wikipedia: XMLHttpRequest](http://en.wikipedia.org/wiki/XMLHttpRequest)
174 Fired when a request doesn't change state for `options.timeout` milliseconds.
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',
193 onRequest: function(){
194 myElement.set('text', 'loading...');
196 onSuccess: function(responseText){
197 myElement.set('text', responseText);
199 onFailure: function(){
200 myElement.set('text', 'Sorry, your request failed :(');
204 document.id('myLink').addEvent('click', function(event){
206 myRequest.send('userid=' + this.get('data-userid'));
211 Request Method: setHeader {#Request:setHeader}
212 --------------------------------------
214 Add or modify a header for the request. It will not override headers from the options.
218 myRequest.setHeader(name, value);
222 1. name - (*string*) The name for the header.
223 2. value - (*string*) The value to be assigned.
227 * (*object*) This Request instance.
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.
241 myRequest.getHeader(name);
245 1. name - (*string*) The name of the header to retrieve the value of.
249 * (*string*) The value of the retrieved header.
250 * (*null*) `null` if the header is not found.
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')
258 Request Method: send {#Request:send}
259 ----------------------------
261 Opens the Request connection and sends the provided data with the specified options.
265 myRequest.send([options]);
269 1. options - (*object*, optional) The options for the sent Request. Will also accept data as a query string for compatibility reasons.
273 * (*object*) This Request instance.
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.
289 - `post()` and `POST()`
290 - `get()` and `GET()`
291 - `put()` and `PUT()`
292 - `delete()` and `DELETE()`
293 - `patch()` and `PATCH()`
294 - `head()` and `HEAD()`
298 myRequest.post([data]);
302 1. data - (*string*, optional) Equivalent with the `data` option of Request.
306 * (*object*) This Request instance.
310 var myRequest = new Request({url: 'http://localhost/some_url'});
312 myRequest.post('save=username&name=John');
313 //...is equivalent to:
316 data: 'save=username&name=John'
319 myRequest.get('save=username&name=John');
320 //...is equivalent to:
323 data: 'save=username&name=John'
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.
344 * (*object*) This Request instance.
348 var myRequest = new Request({url: 'mypage.html', method: 'get'}).send('some=data');
351 Request Method: isRunning {#Request:isRunning}
352 --------------------------------
354 Returns true if the request is currently running
358 myRequest.isRunning()
362 * (*boolean*) True if the request is running
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 -------------------------------------------------
381 Sets a default Request instance for an Element. This is useful when handling forms.
385 el.set('send'[, options]);
389 1. options - (*object*) The Request options.
393 * (*element*) The original element.
397 myForm.set('send', {url: 'contact.php', method: 'get'});
398 myForm.send(); //Sends the form.
402 Returns the previously set Request instance (or a new one with default options).
410 1. property - (*string*) the Request property argument.
414 * (*object*) The Request instance.
418 el.set('send', {method: 'get'});
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.
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".
443 * (element) This Element.
449 <form id="myForm" action="submit.php">
451 <input name="email" value="bob@bob.com" />
452 <input name="zipCode" value="90210" />
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