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 * 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
44 Fired when the Request is sent.
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).
56 onLoadstart(event, xhr)
60 1. event - (Event) The loadstart event.
61 2. xhr - (XMLHttpRequest) The transport instance.
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).
69 onProgress(event, xhr)
73 1. event - (Event) The progress event, containing currently downloaded bytes and total bytes.
74 2. xhr - (XMLHttpRequest) The transport instance.
78 var myRequest = new Request({
80 onProgress: function(event, xhr) {
81 var loaded = event.loaded, total = event.total;
83 console.log(parseInt(loaded / total * 100, 10));
91 - [MDC: nsIDOMProgressEvent](https://developer.mozilla.org/en/XPCOM_Interface_Reference/nsIDOMProgressEvent)
95 Fired when the Request is completed.
103 Fired when a request has been cancelled.
111 Fired when the Request is completed successfully.
115 onSuccess(responseText, responseXML)
119 1. responseText - (*string*) The returned text from the request.
120 2. responseXML - (*mixed*) The response XML from the request.
124 Fired when the request failed (error status code).
132 xhr - (XMLHttpRequest) The transport instance.
136 Fired when setting a request header fails.
140 onException(headerName, value)
144 1. headerName - (*string*) The name of the failing header.
145 2. value - (*string*) The value of the failing header.
149 * response - (*object*) Object with text and XML as keys. You can access this property in the 'success' event.
153 * (*object*) A new Request instance.
157 var myRequest = new Request({method: 'get', url: 'requestHandler.php'});
158 myRequest.send('name=john&lastname=dorian');
162 - [Wikipedia: XMLHttpRequest](http://en.wikipedia.org/wiki/XMLHttpRequest)
166 Fired when a request doesn't change state for `options.timeout` milliseconds.
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',
185 onRequest: function(){
186 myElement.set('text', 'loading...');
188 onSuccess: function(responseText){
189 myElement.set('text', responseText);
191 onFailure: function(){
192 myElement.set('text', 'Sorry, your request failed :(');
196 document.id('myLink').addEvent('click', function(event){
198 myRequest.send('userid=' + this.get('data-userid'));
203 Request Method: setHeader {#Request:setHeader}
204 --------------------------------------
206 Add or modify a header for the request. It will not override headers from the options.
210 myRequest.setHeader(name, value);
214 1. name - (*string*) The name for the header.
215 2. value - (*string*) The value to be assigned.
219 * (*object*) This Request instance.
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.
233 myRequest.getHeader(name);
237 1. name - (*string*) The name of the header to retrieve the value of.
241 * (*string*) The value of the retrieved header.
242 * (*null*) `null` if the header is not found.
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')
250 Request Method: send {#Request:send}
251 ----------------------------
253 Opens the Request connection and sends the provided data with the specified options.
257 myRequest.send([options]);
261 1. options - (*object*, optional) The options for the sent Request. Will also accept data as a query string for compatibility reasons.
265 * (*object*) This Request instance.
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.
281 - `post()` and `POST()`
282 - `get()` and `GET()`
283 - `put()` and `PUT()`
284 - `delete()` and `DELETE()`
288 myRequest.post([data]);
292 1. data - (*string*, optional) Equivalent with the `data` option of Request.
296 * (*object*) This Request instance.
300 var myRequest = new Request({url: 'http://localhost/some_url'});
302 myRequest.post('save=username&name=John');
303 //...is equivalent to:
306 data: 'save=username&name=John'
309 myRequest.get('save=username&name=John');
310 //...is equivalent to:
313 data: 'save=username&name=John'
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.
333 * (*object*) This Request instance.
337 var myRequest = new Request({url: 'mypage.html', method: 'get'}).send('some=data');
340 Request Method: isRunning {#Request:isRunning}
341 --------------------------------
343 Returns true if the request is currently running
347 myRequest.isRunning()
351 * (*boolean*) True if the request is running
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 -------------------------------------------------
370 Sets a default Request instance for an Element. This is useful when handling forms.
374 el.set('send'[, options]);
378 1. options - (*object*) The Request options.
382 * (*element*) The original element.
386 myForm.set('send', {url: 'contact.php', method: 'get'});
387 myForm.send(); //Sends the form.
391 Returns the previously set Request instance (or a new one with default options).
399 1. property - (*string*) the Request property argument.
403 * (*object*) The Request instance.
407 el.get('send', {method: 'get'});
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.
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".
432 * (element) This Element.
438 <form id="myForm" action="submit.php">
440 <input name="email" value="bob@bob.com" />
441 <input name="zipCode" value="90210" />
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