Eight Weeks of Prototype: Week 5, Ajax with Prototype
Request Options
There are a number of different options you can pass to Ajax.Request that allow you to control specifically how the sub-request should be performed, or how its response should be handled. Although there are quite a number of different options, I'll just cover the main ones here. For details on all available options, refer to the documentation at http://prototypejs.org/api/ajax/options.
In order to use these options, you typically create a JavaScript object in which you specify whichever options are required. My own preference is to call this variable options, but it doesn't really matter. You then pass this variable as the second argument to Ajax.Request (the first argument is the URL to request).
Listing 4 shows an example of how to specify the request options to pass to Ajax.Request. My own personal preference is to create the options separately from the call to Ajax.Request, since it makes the code slightly easier to read.
// method 1: create options separate to request var url = '/url/to/request'; var options = { // specify one or more options here }; new Ajax.Request(url, options); // method 2: specify all options inline new Ajax.Request('/url/to/request', { // specify one or more options here });
Now that you know how to create the options, I'll cover the most important options available.
-
method: This specifies the type of HTTP request to perform. The typical values for this arepostorget. If you don't specify this option,postis used. As always, if you are sending data back to the server that may affect the state of the application (e.g. updating data in the database) you should usepost. -
parameters: This option specifies any form data you would like to include in your request. This value can be a string or you can pass an object, which Prototype will automatically serialize and escape for you. This is demonstrated below. -
postBody: If you're performing a request with amethodofpost, then you can use this option to hold the post data. My own preference is just to use theparametersoption, since it will be used for a post request ifpostBodyis left empty.
Listing 5 shows an example of specifying these options for Ajax.Request. Take note of how the parameters option is specified. The second method is preferred since it not only looks cleaner but ensures your values are encoded properly.
// method 1: create parameters as a string var url = '/url/to/request'; var options = { method : 'post', parameters : 'name=Quentin&country=Australia' }; new Ajax.Request(url, options); // method 2: create parameters as an object var url = '/url/to/request'; var options = { method : 'post', parameters : { name : 'Quentin', country : 'Australia' } }; new Ajax.Request(url, options);


![Prototype and Scriptaculous in Action [Ajax]](http://ecx.images-amazon.com/images/I/51u%2B5Y4BSLL._SL75_.jpg)