PrototypeMerge

our complete prototype documenation in one page

Created by: xing, Last modification: 28 Dec 2005 (00:35 UTC) by Stephan Borg
Here you can find all our Prototype Documentation on one massive page.

Complete Protoype Documenation

This is Documentation for the Javascript library Prototype.


Prototype is a JavaScript framework that aims to ease development of dynamic web applications. Featuring a unique, easy-to-use toolkit for class-driven development and the nicest Ajax library around, Prototype is quickly becoming the codebase of choice for Web 2.0 developers everywhere.

Please be advised that prototype can adversely effect some existing javascripts and in places it secretly modifies some of JavaScripts default behavior. Before proceeding with prototype it is worth considering James Mc Parlane's Rejection of prototype.

The Documentation is split among the following pages:

Prototype Use In Bitweaver

You can find Bitweaver Packages that use Prototype and instructions for including the Prototype library in your package here: PrototypeUseInBitweaver

Prototype Tutorials and Examples

There are some examples in the documentation here on bw.o, but here are some more sample uses of Prototype found around the web:
Easy AJAX with Prototype [24-ways.org]
Prototype Library Info [blogs.ebusiness-apps.com]
Quick Guide To Prototype [particletree.com]
Debugging AJAX Requests in Prototype [ajaxian.com]

Credits and About

This documentation is based on the original documentation here:
http://www.sergiopereira.com/articles/prototype.js.html

We hope to make this documenation more accessible by using a wiki for easy access and maintenance.

The utility functions


The library comes with many predefined objects and utility functions. The obvious goal of these functions is to save you a lot of repeated typing and idioms.

Using the $() function


The $() function is a handy shortcut to the all-too-frequent document.getElementById() function of the DOM. Like the DOM function, this one returns the element that has the id passed as an argument.

Unlike the DOM function, though, this one goes further. You can pass more than one id and $() will return an Array object with all the requested elements. The example below should illustrate this.


<html>
    <head>
        <title> Test Page </title>
        <script src="prototype-1.3.1.js"></script>

        <script>
            function test1() {
                var d = $('myDiv');
                alert(d.innerHTML);
            }

            function test2() {
                var divs = $('myDiv','myOtherDiv');
                for(i=0; i<divs.length; i++) {
                    alert(divs[i].innerHTML);
                }
            }
        </script>
    </head>

    <body>
        <div id="myDiv">
            <p>This is a paragraph</p>
        </div>
        <div id="myOtherDiv">
            <p>This is another paragraph</p>
        </div>

        <input type="button" value=Test1 onclick="test1();"><br>
        <input type="button" value=Test2 onclick="test2();"><br>
    </body>
</html>


Another nice thing about this function is that you can pass either the id string or the element object itself, which makes this function very useful when creating other functions that can also take either form of argument.

Using the $F() function


The $F() function is a another welcome shortcut. It returns the value of any field input control, like text boxes or drop-down lists. The function can take as argument either the element id or the element object itself.


<script>
    function test3() {
        alert( $F('userName') );
    }
</script>

<input type="text" id="userName" value="Joe Doe"><br>
<input type="button" value=Test3 onclick="test3();"><br>


Using the Try.these() function


The Try.these() function makes it easy when you want to, ahem, try different function calls until one of them works. It takes a number of functions as arguments and calls them one by one, in sequence, until one of them works, returning the result of that successful function call.

In the example below, the function xmlNode.text works in some browsers, and xmlNode.textContent works in the other browsers. Using the Try.these() function we can return the one that works.


<script>
    function getXmlNodeValue(xmlNode){
        return Try.these(
            function() {return xmlNode.text;},
            function() {return xmlNode.textContent;}
        );
    }
</script>



Extensions to various classes


This collection of classes and functions extends existing Javascript classes and functions. They simplfy such things as manipulating text, adding keyboard commands, adding inheretance, and other random things.

Extensions to the JavaScript classes


One of the ways the prototype.js library adds functionality is by extending the existing JavaScript classes.

Extensions for the Object class


Method Kind Arguments Description
extend(destination, source) static destination: any object, source: any object Provides a way to implement inheritance by copying all properties and methods from source to destination.
extend(object) instance any object Provides a way to implement inheritance by copying all properties and methods from the given object.


Extensions for the Number class


Method Kind Arguments Description
toColorPart() instance (none) Returns the hexadecimal representation of the number. Useful when converting the RGB components of a color into its HTML representation.


Extensions for the Function class


Method Kind Arguments Description
bind(object) instance object: the object that owns the method Returns an instance of the function pre-bound to the function(=method) owner object. The returned function will have the same arguments as the original one.
bindAsEventListener(object) instance object: the object that owns the method Returns an instance of the function pre-bound to the function(=method) owner object.The returned function will have the current event object as its argument.


Let's see one of these extensions in action.


<input type=checkbox id=myChk value=1 /> Test?
<script>
    //declaring the class
    var CheckboxWatcher = Class.create();

    //defining the rest of the class implmentation
    CheckboxWatcher.prototype = {
        initialize: function(chkBox, message) {
            this.chkBox = $(chkBox);
            this.message = message;
            //assigning our method to the event
            this.chkBox.onclick = this.showMessage.bindAsEventListener(this);
        },

        showMessage: function(evt) {
            alert(this.message + ' (' + evt.type + ')');
        }
    };

    var watcher = new CheckboxWatcher('myChk', 'Changed');
</script>


Extensions for the String class


Method Kind Arguments Description
stripTags() instance (none) Returns the string with any HTML or XML tags removed
escapeHTML() instance (none) Returns the string with any HTML markup characters properly escaped
unescapeHTML() instance (none) The reverse of escapeHTML()


Extensions for the document DOM object


Method Kind Arguments Description
getElementsByClassName(className) instance className: name of a CSS class associated with the elements Returns all the elements that are associated with the given class name.


Extensions for the Event object


Property Type Description
KEY_BACKSPACE Number 8: Constant. Code for the Backspace key.
KEY_TAB Number 9: Constant. Code for the Tab key.
KEY_RETURN Number 13: Constant. Code for the Return key.
KEY_ESC Number 27: Constant. Code for the Esc key.
KEY_LEFT Number 37: Constant. Code for the Left arrow key.
KEY_UP Number 38: Constant. Code for the Up arrow key.
KEY_RIGHT Number 39: Constant. Code for the Right arrow key.
KEY_DOWN Number 40: Constant. Code for the Down arrow key.
KEY_DELETE Number 46: Constant. Code for the Delete key.
observers: Array List of cached observers. Part of the internal implementation details of the object.


Method Kind Arguments Description
element(event) static event: an Event object Returns element that originated the event.
isLeftClick(event) static event: an Event object Returns true if the left mouse button was clicked.
pointerX(event) static event: an Event object Returns the x coordinate of the mouse pointer on the page.
pointerY(event) static event: an Event object Returns the y coordinate of the mouse pointer on the page.
stop(event) static event: an Event object Use this function to abort the default behavior of an event and to suspend its propagation.
findElement(event, tagName) static event: an Event object, tagName: name of the desired tag. Traverses the DOM tree upwards, searching for the first element with the given tag name, starting from the element that originated the event.
observe(element, name, observer, useCapture) static element: object or id, name: event name (like 'click', 'load', etc), observer: function to handle the event, useCapture: if true, handles the event in the capture phase and if false in the bubbling phase. Adds an event handler function to an event.
stopObserving(element, name, observer, useCapture) static element: object or id, name: event name (like 'click'), observer: function that is handling the event, useCapture: if true handles the event in the capture phase and if false in the bubbling phase. Removes an event handler from the event.
_observeAndCache(element, name, observer, useCapture) static   Private method, do not worry about it.
unloadCache() static (none) Private method, do not worry about it. Clears all cached observers from memory.


Let's see how to use this object to add an event handler to the load event of the window object.


<script>
    Event.observe(window, 'load', showMessage, false);

    function showMessage() {
      alert('Page loaded.');
    }
</script>


New objects and classes defined by prototype.js


Another way the library helps you is by providing many objects implement both support for object oriented designs and common functionality in general.

The PeriodicalExecuter object


This object provides the logic for calling a given function repeatedly, at a given interval.

Method Kind Arguments Description
ctor(callback, interval) constructor callback: a parameterless function, interval: number of seconds Creates one instance of this object that will call the function repeatedly.


Property Type Description
callback Function() The function to be called. No parameters will be passed to it.
frequency Number This is actually the interval in seconds
currentlyExecuting Boolean Indicates if the function call is in progress


The Prototype object


The Prototype object does not have any important role, other than declaring the version of the library being used.

Property Type Description
Version String The version of the library
emptyFunction Function() An empty function object


The Class object


The Class object is used when declaring the other classes in the library. Using this object when declaring a class causes the to new class to support an initialize() method, which serves as the constructor.

See the sample below.


<script>
    //declaring the class
    var MySampleClass = Class.create();

    //defining the rest of the class implmentation
    MySampleClass.prototype = {
        initialize: function(message) {
            this.message = message;
        },

        showMessage: function(ajaxResponse) {
            alert(this.message);
        }
    };

    //now, let's instantiate and use one object
    var myTalker = new MySampleClass('hi there.');
    myTalker.showMessage(); //displays alert
</script>


Method Kind Arguments Description
create(*) instance (any) Defines a constructor for a new class



The following are objects and functions of the Prototype library that simplify the tricky code that is involved in manipulating Dom Elements, such as text, divs, forms, fields, etc.

These functions are great for changing text on a page, monitoring changes made to forms, and adding and removing addition page parts.

Also see the PrototypeUtilityFunctions, some of which are handy to use when manipulating Elements.

HTML and Basic Element Manipulation

The Element object


This object provides some utility functions for manipulating elements in the DOM.

Method Kind Arguments Description
toggle(elem1 [, elem2 [, elem3 ...]]) instance elemN: element object or id Toggles the visibility of each passed element.
hide(elem1 [, elem2 [, elem3 ...]]) instance elemN: element object or id Hides each element by setting its style.display to 'none'.
show(elem1 [, elem2 [, elem3 ...]]) instance elemN: element object or id Shows each element by resetting its style.display to ''.
remove(element) instance element: element object or id Removes the element from the document.
getHeight(element) instance element: element object or id Returns the offsetHeight of the element
addClassName(element, className) instance element: element object or id, className: name of a CSS class Adds the given class name to the element's class names.
hasClassName(element, className) instance element: element object or id, className: name of a CSS class Returns true if the element has the given class name as one of its class names.
removeClassName(element, className) instance element: element object or id, className: name of a CSS class Removes the given class name from the element's class names.
cleanWhitespace(element) instance element: element object or id Removes any white space text node children of the element


The Abstract object


This object serves as the root for other classes in the library. It does not have any properties or methods. The classes defined in this object are also treated as traditional abstract classes.

The Abstract.Insertion class


This class is used as the base class for the other classes that will provide dynamic content insertion. This class is used like an abstract class.

Method Kind Arguments Description
ctor(element, content) constructor element: element object or id, content: HTML to be inserted Creates an object that will help with dynamic content insertion.


Property Type Kind Description
adjacency String static, parameter Parameter that specifies where the content will be placed relative to the given element. The possible values are: 'beforeBegin', 'afterBegin', 'beforeEnd', and 'afterEnd'.
element Object instance The element object that the insertion will be made relative to.
content String instance The HTML that will be inserted.

The Insertion object


This object serves as the root for other classes in the library. It does not have any properties or methods. The classes defined in this object are also treated as traditional abstract classes.

The Insertion.Before class


Inherits from Abstract.Insertion

Inserts HTML before an element.

Method Kind Arguments Description
ctor(element, content) constructor element: element object or id, content: HTML to be inserted Inherited from Abstract.Insertion. Creates an object that will help with dynamic content insertion.


The following code


<br>Hello, <span id="person" style="color:red;">Wiggum. How is it going?</span>
<script> new Insertion.Before('person', 'Chief '); </script>


Will change the HTML to


<br>Hello, Chief <span id="person" style="color:red;">Wiggum. How is it going?</span>


The Insertion.Top class


Inherits from Abstract.Insertion

Inserts HTML as the first child under an element. The content will be right after the opening tag of the element.

Method Kind Arguments Description
ctor(element, content) constructor element: element object or id, content: HTML to be inserted Inherited from Abstract.Insertion. Creates an object that will help with dynamic content insertion.


The following code


<br>Hello, <span id="person" style="color:red;">Wiggum. How is it going?</span>
<script> new Insertion.Before('person', 'Mr. '); </script>


Will change the HTML to


<br>Hello, <span id="person" style="color:red;">Mr. Wiggum. How is it going?</span>


The Insertion.Bottom class


Inherits from Abstract.Insertion

Inserts HTML as the last child under an element. The content will be right before the element's closing tag.

Method Kind Arguments Description
ctor(element, content) constructor element: element object or id, content: HTML to be inserted Inherited from Abstract.Insertion. Creates an object that will help with dynamic content insertion.


The following code


<br>Hello, <span id="person" style="color:red;">Wiggum. How is it going?</span>
<script> new Insertion.Before('person', ' What's up?'); </script>


Will change the HTML to


<br>Hello, <span id="person" style="color:red;">Wiggum. How is it going? What's up?</span>


The Insertion.After class


Inherits from Abstract.Insertion

Inserts HTML right after the element's closing tag.

Method Kind Arguments Description
ctor(element, content) constructor element: element object or id, content: HTML to be inserted Inherited from Abstract.Insertion. Creates an object that will help with dynamic content insertion.


The following code


<br>Hello, <span id="person" style="color:red;">Wiggum. How is it going?</span>
<script> new Insertion.Before('person', ' Are you there?'); </script>


Will change the HTML to


<br>Hello, <span id="person" style="color:red;">Wiggum. How is it going?</span> Are you there?


The Position object (preliminary documentation)


This object provides a host of functions that help when working with element positioning.

Method Kind Arguments Description
prepare() instance (none) Adjusts the deltaX and deltaY properties to accommodate changes in the scroll position. Remember to call this method before any calls to withinIncludingScrolloffset after the page scrolls.
realOffset(element) instance element: object Returns an Array with the correct scroll offsets of the element, including any scroll offsets that affect the element. The resulting array is similar to total_scroll_left, total_scroll_top
cumulativeOffset(element) instance element: object Returns an Array with the correct positioning offsets of the element, including any offsets that are imposed by positioned parent elements. The resulting array is similar to total_offset_left, total_offset_top
within(element, x, y) instance element: object, x and y: coordinates of a point Tests if the given point coordinates are inside the bounding rectangle of the given element
withinIncludingScrolloffsets(element, x, y) instance element: object, x and y: coordinates of a point  
overlap(mode, element) instance mode: 'vertical' or 'horizontal', element: object within() needs to be called right before calling this method. This method will return a decimal number between 0.0 and 1.0 representing the fraction of the coordinate that overlaps on the element. As an example, if the element is a square DIV with a 100px side and positioned at (300, 300), then within(divSquare, 330, 330); overlap('vertical', divSquare); should return 0.10, meaning that the point is at the 10% (30px) mark from the top border of the DIV.
clone(source, target) instance source: element object or id, target: element object or id Resizes and repositions the target element identically to the source element.


Form and Field Element Manipulation

The Field object


This object provides some utility functions for working with input fields in forms.

Method Kind Arguments Description
clear(field1 [, field2 [, field3 ...]]) instance fieldN: field element object or id Clears the value of each passed form field element.
present(field1 [, field2 [, field3 ...]]) instance fieldN: field element object or id Returns true only if all forms fields contain non-empty values.
focus(field) instance field: field element object or id Moves the input focus to the given form field.
select(field) instance field: field element object or id Selects the value in fields that support text selection
activate(field) instance field: field element object or id Move the focus and selects the value in fields that support text selection


The Form object


This object provides some utility functions for working with data entry forms and their input fields.

Method Kind Arguments Description
serialize(form) instance form: form element object or id Returns a url-formatted list of field names and their values, like 'field1=value1&field2=value2&field3=value3'
getElements(form) instance form: form element object or id Returns an Array containing all the input fields in the form.
getInputs(form [, typeName , name]) instance form: form element object or id, typeName: the type of the input element, name: the name of the input element. Returns an Array containing all the <input> elements in the form. Optionally, the list can be filtered by the type or name attributes of the elements.
disable(form) instance form: form element object or id Disables all the input fields in the form.
enable(form) instance form: form element object or id Enables all the input fields in the form.
focusFirstElement(form) instance form: form element object or id Activates the first visible, enabled input field in the form.
reset(form) instance form: form element object or id Resets the form. The same as calling the reset() method of the form object.


The Form.Element object


This object provides some utility functions for working with form elements, visible or not.

Method Kind Arguments Description
serialize(element) instance element: element object or id Returns the element's name=value pair, like 'elementName=elementValue'
getValue(element) instance element: element object or id Returns the value of the element.


The Form.Element.Serializers object


This object provides some utility functions that are used internally in the library to assist extracting the current value of the form elements.

Method Kind Arguments Description
inputSelector(element) instance element: object or id of a form element that has the checked property, like a radio button or checkbox. Returns an Array with the element's name and value, like elementName', 'elementValue>'elementName', 'elementValue'
textarea(element) instance element: object or id of a form element that has the value property, like a textbox, button or password field. Returns an Array with the element's name and value, like elementName', 'elementValue>'elementName', 'elementValue'
select(element) instance element: object or id of a <select> element Returns an Array with the element's name and all selected options' values or texts, like elementName', 'selOpt1 selOpt4 selOpt9>'elementName', 'selOpt1 selOpt4 selOpt9'


Element Listening

The Abstract.TimedObserver class


This class is used as the base class for the other classes that will monitor one element until its value (or whatever property the derived class defines) changes. This class is used like an abstract class.

Subclasses can be created to monitor things like the input value of an element, or one of the style properties, or number of rows in a table, or whatever else you may be interested in tracking changes to.

||Method | Kind | Arguments | Description
ctor(element, frequency, callback) | constructor | element: element object or id, frequency: interval in seconds, callback: function to be called when the element changes | Creates an object that will monitor the element.


The Ajax object


The Ajax object is a pre-defined object, created by the library to wrap and simplify the tricky code that is involved when writing AJAX functionality. This object serves as the root for many other classes that provide AJAX functionality. This object contains a number of classes that provide encapsulated AJAX logic.

Method Kind Arguments Description
getTransport() instance (none) Returns a new XMLHttpRequest object


The Ajax.Base class


This class is used as the base class for the other classes defined in the Ajax object.

Method Kind Arguments Description
setOptions(options) instance options: AJAX options Sets the desired options for the AJAX operation
responseIsSuccess() instance (none) Returns true if the AJAX operation succeeded, false otherwise
responseIsFailure() instance (none) The opposite of responseIsSuccess().


The Ajax.Request class


Inherits from Ajax.Base

Encapsulates AJAX operations

Property Type Kind Description
Events Array static List of possible events/statuses reported during an AJAX operation. The list contains: 'Uninitialized', 'Loading', 'Loaded', 'Interactive', and 'Complete.'
transport XMLHttpRequest instance The XMLHttpRequest object that carries the AJAX operation


Method Kind Arguments Description
ctor(url, options) constructor url: the url to be fetched, options: AJAX options Creates one instance of this object that will call the given url using the given options. Important: It is worth noting that the chosen url is subject to the borwser's security settings. In many cases the browser will not fetch the url if it is not from the same host (domain) as the current page. You should ideally use only local urls to avoid having to configure or restrict the user's browser. (Thanks Clay).
request(url) instance url: url for the AJAX call This method is typically not called externally. It is already called during the constructor call.
setRequestHeaders() instance (none) This method is typically not called externally. It is called by the object itself to assemble the HTTP header that will be sent during the HTTP request.
onStateChange() instance (none) This method is typically not called externally. It is called by the object itself when the AJAX call status changes.
respondToReadyState(readyState) instance readyState: state number (1 to 4) This method is typically not called externally. It is called by the object itself when the AJAX call status changes.


The options argument object


An important part of the AJAX operations is the options argument. There's no options class per se. Any object can be passed, as long as it has the expected properties. It is common to create anonymous objects just for the AJAX calls.

Property Type Default Description
method String 'post' Method of the HTTP request
parameters String The url-formatted list of values passed to the request
asynchronous Boolean true Indicates if the AJAX call will be made asynchronously
postBody String undefined Content passed to in the request's body in case of a HTTP POST
requestHeaders Array undefined List of HTTP headers to be passed with the request. This list must have an even number of items, any odd item is the name of a custom header, and the following even item is the string value of that header. Example:my-header1', 'this is the value', 'my-other-header', 'another value''>'my-header1', 'this is the value', 'my-other-header', 'another value'
onXXXXXXXX Function(XMLHttpRequest) undefined Custom function to be called when the respective event/status is reached during the AJAX call. Example var myOpts = {onComplete: showResponse, onLoaded: registerLoaded};. The function used will receive one argument, containing the XMLHttpRequest object that is carrying the AJAX operation.
onSuccess Function(XMLHttpRequest) undefined Custom function to be called when the AJAX call completes successfully. The function used will receive one argument, containing the XMLHttpRequest object that is carrying the AJAX operation.
onFailure Function(XMLHttpRequest) undefined Custom function to be called when the AJAX call completes with error. The function used will receive one argument, containing the XMLHttpRequest object that is carrying the AJAX operation.
insertion Function(Object, String) null Function to be called to inject the returned text into an element. The function will be called with two arguments, the element object to be updated and the response text Applies only to Ajax.Updater objects.
evalScripts Boolean undefined, false Determines if script blocks will be evaluated when the response arrives. Applies only to Ajax.Updater objects.
decay Number undefined, 1 Determines the progressive slowdown in a Ajax.PeriodicalUpdater object refresh rate when the received response is the same as the last one. For example, if you use 2, after one of the refreshes produces the same result as the previous one, the object will wait twice as much time for the next refresh. If it repeats again, the object will wait four times as much, and so on. Leave it undefined or use 1 to avoid the slowdown.


The Ajax.Updater class


Inherits from Ajax.Request

Used when the requested url returns HTML that you want to inject directly in a specific element of your page. You can also use this object when the url returns <script> blocks that will be evaluated upon arrival. Use the evalScripts option to work with scripts.

Property Type Kind Description
ScriptFragment String static A regular expression to identify scripts
containers Object instance This object contains two properties: containers.success will be used when the AJAX call succeeds, and containers.failure will be used otherwise.


Method Kind Arguments Description
ctor(container, url, options) constructor container:this can be the id of an element, the element object itself, or an object with two properties - object.success element (or id) that will be used when the AJAX call succeeds, and object.failure element (or id) that will be used otherwise. url: the url to be fetched, options: AJAX options Creates one instance of this object that will call the given url using the given options.
updateContent() instance (none) This method is typically not called externally. It is called by the object itself when the response is received. It will update the appropriate element with the HTML or call the function passed in the insertion option. The function will be called with two arguments, the element to be updated and the response text.


The Ajax.PeriodicalUpdater class


Inherits from Ajax.Base

This class repeatedly instantiates and uses an Ajax.Updater object to refresh an element on the page, or to perform any of the other tasks the Ajax.Updater can perform. Check the Ajax.Updater reference for more information.

Property Type Kind Description
container Object instance This value will be passed straight to the Ajax.Updater's constructor.
url String instance This value will be passed straight to the Ajax.Updater's constructor.
frequency Number instance Interval (not frequency) between refreshes, in seconds. Defaults to 2 seconds. This number will be multiplied by the current decay when invoking theAjax.Updater object
decay Number instance Keeps the current decay level applied when re-executing the task
updater Ajax.Updater instance The most recently used Ajax.Updater object
timer Object instance The JavaScript timer being used to notify the object when it is time for the next refresh.


Method Kind Arguments Description
ctor(container, url, options) constructor container:this can be the id of an element, the element object itself, or an object with two properties - object.success element (or id) that will be used when the AJAX call succeeds, and object.failure element (or id) that will be used otherwise. url: the url to be fetched, options: AJAX options Creates one instance of this object that will call the given url using the given options.
start() instance (none) This method is typically not called externally. It is called by the object itself to start performing its periodical tasks.
stop() instance (none) This method is typically not called externally. It is called by the object itself to stop performing its periodical tasks.
updateComplete() instance (none) This method is typically not called externally. It is called by the currently used Ajax.Updater after if completes the request. It is used to schedule the next refresh.
onTimerEvent() instance (none) This method is typically not called externally. It is called internally when it is time for the next update.


Use Examples


Using the Ajax.Request class


If you are not using any helper library, you are probably writing a whole lot of code to create a XMLHttpRequest object and then track its progress asynchronously, then extract the response and process it. And consider yourself lucky if you do not have to support more than one
type of browser.

To assist with AJAX functionality, the library defines the Ajax.Request class.

Let's say you have an application that can communicate with the server via the url http://yoursever/app/get_sales?empID=1234&year=1998, which returns an XML response like the following.


<?xml version="1.0" encoding="utf-8" ?>
<ajax-response>
    <response type="object" id="productDetails">
        <monthly-sales>
            <employee-sales>
                <employee-id>1234</employee-id>
                <year-month>1998-01</year-month>
                <sales>$8,115.36</sales>
            </employee-sales>
            <employee-sales>
                <employee-id>1234</employee-id>
                <year-month>1998-02</year-month>
                <sales>$11,147.51</sales>
            </employee-sales>
        </monthly-sales>
    </response>
</ajax-response>


Talking to the server to retrieve this XML is pretty simple using an Ajax.Request object. The sample below shows how it can be done.


<script>
    function searchSales() {
        var empID = $F('lstEmployees');
        var y = $F('lstYears');
        var url = 'http://yoursever/app/get_sales';
        var pars = 'empID=' + empID + '&year=' + y;
        var myAjax = new Ajax.Request(
            url,
            {method: 'get', parameters: pars, onComplete: showResponse}
        );
    }

    function showResponse(originalRequest) {
        //put returned XML in the textarea
        $('result').value = originalRequest.responseText;
    }
</script>

<select id="lstEmployees" size="10" onchange="searchSales()">
    <option value="5">Buchanan, Steven</option>
    <option value="8">Callahan, Laura</option>
    <option value="1">Davolio, Nancy</option>
</select>
<select id="lstYears" size="3" onchange="searchSales()">
    <option selected="selected" value="1996">1996</option>
    <option value="1997">1997</option>
    <option value="1998">1998</option>
</select>
<br>
<textarea id=result cols=60 rows=10 ></textarea>


Can you see the second parameter passed to the constructor of the Ajax.Request object? The parameter {method: 'get', parameters: pars, onComplete: showResponse} represents an anonymous object in literal notation. What it means is that we are passing an object that has a property named method that contains the string 'get', another property named parameters that contains the querystring of the HTTP request, and an onComplete property/method containing the function showResponse.

There are a few other properties that you can define and populate in this object, like asynchronous, which can be true or false and determines if the AJAX call to the server will be made asynchronously (the default value is true.)

This parameter defines the options for the AJAX call. In our sample, we are calling the url in the first argument via a HTTP GET command, passing the querystring contained in the variable pars, and the Ajax.Request object will call the showResponse function when it finishes retrieving the response.

As you may know, the XMLHttpRequest reports progress during the HTTP call. This progress can inform four different stages: Loading, Loaded, Interactive, or Complete. You can make the Ajax.Request object call a custom function in any of these stages, the Complete being the most common one. To inform the function to the object, simply provide property/methods named onXXXXX in the request options, just like the onComplete from our example. The function you pass in will be called by the object with one argument, which will be the XMLHttpRequest object itself. You can then use this object to get the returned data and maybe check the status property, which will contain the HTTP result code of the call.

Two other interesting options can be used to process the results. We can specify the onSuccess option as a function to be called when the AJAX call executes without errors and, conversily, the onFailure option can be a function to be called when a server error happens. Just like the onXXXXX option functions, these two will also be called passing the XMLHttpRequest object that carried the AJAX call.

Our sample did not process the XML response in any interesting way. We just dumped the XML in the textarea. A typical usage of the response would probably find the desired information inside the XML and update some page elements, or maybe even some sort of XSLT transformation to produce HTML in the page.

For more complete explanations, see the Ajax.Request reference and the options reference.

Using the Ajax.Updater class


If you have a server endpoint that can return information already formatted in HTML, the library makes life even easier for you with the Ajax.Updater class. With it you just inform which element should be filled with the HTML returned from the AJAX call. An example speaks better that I can write.


<script>
    function getHTML() {
        var url = 'http://yourserver/app/getSomeHTML';
        var pars = 'someParameter=ABC';
        var myAjax = new Ajax.Updater('placeholder', url, {method: 'get', parameters: pars});
    }
</script>

<input type=button value=GetHtml onclick="getHTML()">
<div id="placeholder"></div>


As you can see, the code is very similar to the previous example, with the exclusion of the onComplete function and the element id being passed in the constructor. Let's change the code a little bit to illustrate how it is possible to handle server errors on the client.

We will add more options to the call, specifying a function to capture error conditions. This is done using the onFailure option. We will also specify that the placeholder only gets populated in case of a successful operation. To achieve this we will change the first parameter from a simple element id to an object with two properties, success (to be used when everything goes OK) and failure (to be used when things go bad.) We will not be using the failure property in our example, just the reportError function in the onFailure option.


<script>
function getHTML() {
    var url = 'http://yourserver/app/getSomeHTML';
    var pars = 'someParameter=ABC';
    var myAjax = new Ajax.Updater(
        {success: 'placeholder'},
        url,
        {method: 'get', parameters: pars, onFailure: reportError}
    );
}

function reportError(request) {
    alert('Sorry. There was an error.');
}
</script>

<input type=button value=GetHtml onclick="getHTML()">
<div id="placeholder"></div>


If your server logic returns JavaScript code instead of HTML markup, the Ajax.Updater object can evaluate that JavaScript code. To get the object to treat the response as JavaScript, you simply add evalScripts: true; to the list of properties in the last argument of the object constructor.

For more complete explanations, see the Ajax.Updater reference and the options reference.