PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Eight Weeks of Prototype: Week 5, Ajax with Prototype

Request Types

There are three different classes Prototype provides to perform Ajax requests. These are Ajax.Request, Ajax.Updater and Ajax.PeriodicalUpdater.

Ajax.Request

This is the primary class that is used for Ajax, which the other two classes mentioned above use also. Ajax.Request provides a cross-browser solution for performing Ajax requests without requiring that you know how to specifically use XmlHttpRequest.

This class is simple to use – just instantiate it and pass to it the URL you want to send a HTTP request to as the first argument. You can optionally pass a second argument to the constructor which you can use to specify a number of different options. It's pretty rare that you would ever use this class without specifying the second argument, since most of the time you will want to use the response in some way.

Listing 1 shows an example of performing an Ajax request. For now, the options are an empty JavaScript object, but in the next section I will cover the different options that are available for you to specify. These also apply to the Ajax.Updater and Ajax.PeriodicalUpdater classes we will look at shortly.

Note: If you try out this example, your sub-request will likely result in a 404 file not found error since the requested file does not exist. Try changing the URL to a file you know exists on your server.
Listing 1 A basic Ajax sub-request (listing-1.html)
<html>
    <head>
        <title>A basic Ajax sub-request</title>
        <script type="text/javascript" src="/js/prototype.js"></script>
    </head>
    <body>
        <script type="text/javascript">
            var options = {
                method : 'post'
            }
 
            new Ajax.Request('/path/to/file', options);
        </script>
    </body>
</html>
Note: Ajax.Request is a class, not a function, so you must remember to instantiate the class by including the new keyword.

In the above example, the options object is used to hold the various request options. This may include get or post data to include in the request or instructions on what to do on successful completion (or failure) of the request. In this example, I have set the request method to be post, simply by specifying the method option.

In this example, once the script is requested nothing will happen since we haven't defined any callbacks for handling the response. I will cover this in the next section.

In This Article