Using Prototype JavaScript Library

Sang Shin, sang.shin@sun.com, Sun Microsystems, www.javapassion.com/ajaxcodecamp


This hands-on lab takes you through the basics of using Prototype JavaScript library.  First, you will explore various utitlity functions.  Second, you will modify ajax-validation project to use Ajax.Request function of the Prototype.


Expected duration: 60 minutes


Software Needed

Before you begin, you need to install the following software on your computer. 


OS platforms you can use

Resources


Acknowledgments

This hands-on lab is based on Developer Notes for prototype.js JavaScript tutorial written by Sergio Pereira with the permission from the author.  We thank Sergio for his generosity.

Change Log


Lab Exercises


Exercise 1: Explore Prototype JavaScript utility functions

In this exercise, you are going to learn how to use various utility functions of the Prototype JavaScript library.

  1. Exercise $( ) function
  2. Exercise $F( ) function
  3. Exercise $A( ) function
  4. Exercise $H( ) function
  5. Exercise $R( ) function
  6. Exercise Try.these function

(1.1) Exercise $( ) function

Read description of $() function before you proceed.

0. Start NetBeans IDE. 
1. Open prototypesamplescripts NetBeans project. 

2. Study the dollar.html that uses $() utility function of Prototype.
<HTML>
    <HEAD>
        <TITLE> Test Page </TITLE>
        <script src="prototype-1.4.0.js"></script>

        <script>
    function test1()
    {
        // Get element whose id is 'myDiv' via $()
        var d = $('myDiv');
        alert(d.innerHTML);
    }

    function test2()
    {
        // Get elements into an array via $()
        var divs = $('myDiv','myOtherDiv');
               
        // Display child node of the each item in the array
        for(i=0; i<divs.length; i++)
        {
            alert(divs[i].innerHTML);
        }
    }
        </script>
    </HEAD>

    <BODY>
        <h3> The $() function </h3>
        <hr/>
        <p>
            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.
        </p>
        <hr/>

        <div id="myDiv">
            <p>This is the first paragraph</p>
        </div>
        <div id="myOtherDiv">
            <p>This is the second paragraph</p>
        </div>

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

    </BODY>
</HTML>
Code-1.10: dollar.html

3. Right click dollar.html under prototypesamplescripts->Web Pages and select View. (Figure-1.11 below)


Figure-1.11: View the dollar.html file

4. Observe the browser gets displayed with Test1 and Test2 buttons. (Figure-1.12 below)


Figure-1.12: Result of running dollar.html

5. Press Test1 button and observe only one message gets displayed. (Figure-1.13 below)  Click OK to close the alert message box.


Figure-1.13: Message from a single item

6. Press Test2 button and observe that two messages (from an array of two items) are displayed (Figure-1.14 and Figure-1.5 below)  Click OK to close the alert message box.


Figure-1.14: Message from the first item in the array


Figure-1.15: Message from the 2nd item in the array

Now you are going to add another item to the array.

7. Modify dollar.html as shown in Code-1.16 below.  The code fragments that need to be added are highlighted in bold and blue colored font.

<HTML>
    <HEAD>
        <TITLE> Test Page </TITLE>
        <script src="prototype-1.4.0.js"></script>

        <script>
    function test1()
    {
                // Get element whose id is 'myDiv' via $()
        var d = $('myDiv');
        alert(d.innerHTML);
    }

    function test2()
    {
                // Get elements into an array via $()
        var divs = $('myDiv','myOtherDiv','my3rdDiv');
               
                // Display child node of the each item in the array
        for(i=0; i<divs.length; i++)
        {
            alert(divs[i].innerHTML);
        }
    }
        </script>
    </HEAD>

    <BODY>
        <h3> The $() function </h3>
        <hr/>
        <p>
            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.
        </p>
        <hr/>
       
        <div id="myDiv">
            <p>This is the first paragraph</p>
        </div>
        <div id="myOtherDiv">
            <p>This is the second paragraph</p>
        </div>
        <div id="my3rdDiv">
            <p>This is the third paragraph</p>
        </div>
       
        <input type="button" value=Test1 onclick="test1();"><br><br>
        <input type="button" value=Test2 onclick="test2();"><br><br>

    </BODY>
</HTML>
Code-1.16: Modified dollar.html

8. Select File from top-level menu and select Save (Ctrl+S).  You have to save the change before you can View the modified html file.  Otherwise, your change will not be reflected in the displayed browser.

Figure-1.17: Save the change before viewing it

9. Right click dollar.html under prototypesamplescripts->Web Pages and select View.
10. Pressing Test2 button and observe that it will display 3 alert messages in sequence.


(1.2) Exercise $F( ) function


Read description of $F( ) function before you proceed.

1. Double-click dollarF.html to open it in the source editor.  Please study the code fragments which are highlighted in the bold font.

<HTML>
    <HEAD>
        <TITLE> Test Page </TITLE>
        <script src="prototype-1.4.0.js"></script>

        <script>
            function test3()
           {
                // Display the value of the input form field whose id
                // is "userName"
                alert(  $F('userName')  );
           }
        </script>
    </HEAD>

    <BODY>
        <h3> The $F() function </h3>
        <hr/>
        <p>
            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.
        </p>
   
         // Input form field whose value is set to Joe Doe
        <input type="text" id="userName" value="Joe Doe"><br>
        <input type="button" value=Test3 onclick="test3();"><br>
    </BODY>
</HTML>
Code-1.20: dollarF.html

2. Right click dollarF.html under prototypesamplescripts->Web Pages and select View. (Figure-1.21 below)


Figure-1.21: Value of an input form field is displayed

3. Modify dollarF.html as shown in Code-1.22 below.  The code fragments that need to be added are highlighted in bold and blue colored font.

<HTML>
    <HEAD>
        <TITLE> Test Page </TITLE>
        <script src="prototype-1.4.0.js"></script>

        <script>
            function test3()
           {
                // Display the value of the input form field whose id
                // is "userName"
               alert(  $F('userName')  );
               alert(  $F('myOwnInputField') );
           }
        </script>
    </HEAD>

    <BODY>
        <h3> The $F() function </h3>
        <hr/>
        <p>
            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.
        </p>
   
        <!--Input form field whose value is set to Joe Doe-->
        <input type="text" id="userName" value="Joe Doe"><br>
        <input type="text" id="myOwnInputField" value="Sang Shin"><br>
        <input type="button" value=Test3 onclick="test3();"><br>
    </BODY>
</HTML>
Code-1.22: Modified dollarF.html

4. Select File from top-level menu and select Save (Ctrl+S).
5. Right click dollarF.html under prototypesamplescripts->Web Pages and select View.
6. Observe that you get two alert messages that display "Joe Doe" and "Sang Shin" in sequence.

(1.3) Exercise $A( ) function


Read description of $A( ) function before you proceed.

1. Double-click dollarA.html to open it in the source editor.   Please study the code fragments which are highlighted in the bold font. (Code-1.30 below)

<HTML>
    <HEAD>
        <TITLE> Test Page </TITLE>
        <script src="prototype-1.4.0.js"></script>

        <script>
           function showOptions(){
                // Get all nodes whose tag name is 'option'
                var someNodeList = $('lstEmployees').getElementsByTagName('option');
                // Create an array from the node list
                var nodes = $A(someNodeList);

                // Display name of the node and innerHTML value from the array
                nodes.each(function(node){
                                       alert(node.nodeName + ': ' + node.innerHTML);
                                });
           }
        </script>
    </HEAD>

    <BODY>
        <h3> The $A() function </h3>
        <hr/>
        <p>

            The $A() function converts the single argument it receives into an Array object.

            This function, combined with the extensions for the Array class, makes it easier to convert
            or copy any enumerable list into an Array object. One suggested use is to convert DOM NodeLists
            into regular arrays, which can be traversed more efficiently.
        </p>
   
        <select id="lstEmployees" size="10" >
            <option value="5">Buchanan, Steven</option>
            <option value="8">Callahan, Laura</option>
            <option value="1">Davolio, Nancy</option>
        </select>

        <input type="button" value="Show the options" onclick="showOptions();" >
    </BODY>
</HTML>
Code-1.30: dollarA.html

2. Right click dollarA.html under prototypesamplescripts->Web Pages and select View.  Click Show the options button.
3. Observe that 3 alert messages are displayed each of which displays the values of the 3 options.
4. Modify dollarA.html as shown in Code-1.22 below.  The code fragments that need to be added are highlighted in bold and blue colored font.

<HTML>
    <HEAD>
        <TITLE> Test Page </TITLE>
        <script src="prototype-1.4.0.js"></script>

        <script>
           function showOptions(){
                // Get all nodes whose tag name is 'option'
                var someNodeList = $('lstEmployees').getElementsByTagName('option');
                // Create an array from the node list
                var nodes = $A(someNodeList);

                // Display name of the node and innerHTML value from the array
                nodes.each(function(node){
                                       alert(node.nodeName + ': ' + node.innerHTML);
                                });
           }
        </script>
    </HEAD>

    <BODY>
        <h3> The $A() function </h3>
        <hr/>
        <p>

            The $A() function converts the single argument it receives into an Array object.

            This function, combined with the extensions for the Array class, makes it easier to convert
            or copy any enumerable list into an Array object. One suggested use is to convert DOM NodeLists
            into regular arrays, which can be traversed more efficiently.
        </p>
  
        <select id="lstEmployees" size="10" >
            <option value="5">Buchanan, Steven</option>
            <option value="8">Callahan, Laura</option>
            <option value="1">Davolio, Nancy</option>
            <option value="3">Shin, Sang</option>
        </select>

        <input type="button" value="Show the options" onclick="showOptions();" >
    </BODY>
</HTML>
Code-1.31: Modified dollarA.html

4. Select File from top-level menu and select Save (Ctrl+S).
5. Right click dollarA.html under prototypesamplescripts->Web Pages and select View. Click Show the options button.
6. Observe that you get four alert messages in sequence, the last of which displays "Shin, Sang".

(1.4) Exercise $H( ) function


Read description of $H( ) function before you proceed.

1. Double-click dollarH.html to open it in the source editor.   Please study the lines which are highlighted in the bold font. (Code-1.40 below)

<HTML>
    <HEAD>
        <TITLE> Test Page </TITLE>
        <script src="prototype-1.4.0.js"></script>

        <script>
        function testHash()
       {
              //let's create the object
              var a = {
                       first: 10,
                       second: 20,
                       third: 30
               };

               //now transform it into a hash
               var h = $H(a);
               alert(h.toQueryString()); //displays: first=10&second=20&third=30
       }
        </script>
    </HEAD>

    <BODY>
        <h3> The $H() function </h3>
        <hr/>
        <p>
            The $H() function converts objects into enumerable Hash objects that resemble associative arrays.
           
        </p>
        <input type="button" value="Generate hash" onclick="testHash();" >
    </BODY>
</HTML>
Code-1.40: dollarH.html

2. Right click dollarH.html under prototypesamplescripts->Web Pages and select View
3. Click Generate hash button.
4. Observe the enumeration is converted into query string format and gets displayed as an alert message. Click OK to close the alert message box.


Figure-1.41: Query string format

5. Modify dollarH.html as shown in Code-1.42 below.  The code fragments that need to be added are highlighted in bold and blue colored font.

<HTML>
    <HEAD>
        <TITLE> Test Page </TITLE>
        <script src="prototype-1.4.0.js"></script>

        <script>
        function testHash()
       {
              //let's create the object
              var a = {
                       first: 10,
                       second: 20,
                       third: 30,
                       fourth: 40
               };

               //now transform it into a hash
               var h = $H(a);
               alert(h.toQueryString()); //displays: first=10&second=20&third=30
       }
        </script>
    </HEAD>

    <BODY>
        <h3> The $H() function </h3>
        <hr/>
        <p>
            The $H() function converts objects into enumerable Hash objects that resemble associative arrays.
           
        </p>
        <input type="button" value="Generate hash" onclick="testHash();" >
    </BODY>
</HTML>
Code-1.42: Modified dollarH.html

6. Select File from top-level menu and select Save (Ctrl+S).
7. Right click dollarH.html under prototypesamplescripts->Web Pages and select View.
8. Click Generate hash button.
9. Observe the enumeration is converted into query string format and gets displayed as an alert message. Click OK to close the alert message box.


Figure-1.43: Result

(1.5) Exercise $R( ) function


Read description of $R( ) function before you proceed.

1. Double-click dollarR.html to open it in the source editor.   Please study the lines which are highlighted in the bold font. (Code-1.50 below)

<HTML>
    <HEAD>
        <TITLE> Test Page </TITLE>
        <script src="prototype-1.4.0.js"></script>

        <script>
           function demoDollar_R(){
               var range = $R(10, 15, false);
               range.each(function(value, index){
                                       alert(value);
                                 });
           }
        </script>
    </HEAD>

    <BODY>
        <h3> The $R() function </h3>
        <hr/>
        <p>
            The $R() function is simply a short hand to writing new
            ObjectRange(lowerBound, upperBound, excludeBounds).

            Jump to the ObjectRange class documentation for a complete explanation
            of this class. In the meantime, let's take a look at a simple example
            that also shows the usage of iterators through the each method.
        </p>

        <input type="button" value="Sample Count" onclick="demoDollar_R();" >
    </BODY>
</HTML>
Code-1.50: dollarR.html

2. Right click dollarR.html under prototypesamplescripts->Web Pages and select View
3. Click Sample Count button.
4. Observe that alert message boxes are being displayed starting from number 10 to 15.
5. Modify dollarR.html as shown in Code-1.51 below.  The code fragments that need to be modified are highlighted in bold and blue colored font.

<HTML>
    <HEAD>
        <TITLE> Test Page </TITLE>
        <script src="prototype-1.4.0.js"></script>

        <script>
           function demoDollar_R(){
               var range = $R(10, 16, false);
               range.each(function(value, index){
                                       alert("value=" + value + " index=" + index);
                                 });
           }
        </script>
    </HEAD>

    <BODY>
        <h3> The $R() function </h3>
        <hr/>
        <p>
            The $R() function is simply a short hand to writing new
            ObjectRange(lowerBound, upperBound, excludeBounds).

            Jump to the ObjectRange class documentation for a complete explanation
            of this class. In the meantime, let's take a look at a simple example
            that also shows the usage of iterators through the each method.
        </p>

        <input type="button" value="Sample Count" onclick="demoDollar_R();" >
    </BODY>
</HTML>
Code-1.51: Modified dollarR.html

6. Select File from top-level menu and select Save (Ctrl+S).
7. Click Sample Count button.
8. Observe that alert message boxes are being displayed starting from number 10 to 16 with value and index.

(1.6) Exercise Try.these) function


Read description of Try.these function before you proceed.

1. Double-click Trythese.html to open it in the source editor.   Note that Try.these has two functions, both of which work. 

<HTML>
    <HEAD>
        <TITLE> Test Page </TITLE>
        <script src="prototype-1.4.0.js"></script>

        <script>
        function getXmlNodeValue(){
            var value = Try.these(
                            function() {
                                return 1;
                            },
                            function() {
                                return 2;}
                            );
            alert("value returned = " + value);               
        }
        </script>
    </HEAD>

    <BODY>
        <h3> Try.these </h3>
        <hr/>
        <p>
            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, 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.
        </p>

        <input type="button" value="Try.these" onclick="getXmlNodeValue();" >
    </BODY>
</HTML>
Code-1.60: Trythese.html

2. Right click Trythese.html under prototypesamplescripts->Web Pages and select View
3. Click Try.these button.
4. Observe that alert message box displays 1.
5. Modify Trythese.html as shown in Code-1.61 below.  This is to introduce an error in the first function.

<HTML>
    <HEAD>
        <TITLE> Test Page </TITLE>
        <script src="prototype-1.4.0.js"></script>

        <script>
        function getXmlNodeValue(){
            var value = Try.these(
                            function() {
                                intentionalerror; // intentional error
                                return 1;
                            },
                            function() {
                                return 2;}
                            );
            alert("value returned = " + value);               
        }
        </script>
    </HEAD>

    <BODY>
        <h3> Try.these </h3>
        <hr/>
        <p>
            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, 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.
        </p>

        <input type="button" value="Try.these" onclick="getXmlNodeValue();" >
    </BODY>
</HTML>
Code-1.61: Modified Trythese.html with an intentional error.

6. Select File from top-level menu and select Save (Ctrl+S).
7. Right click Trythese.html under prototypesamplescripts->Web Pages and select View
8. Click Try.these button.
9. Observe that alert message box this time displays 2.


Summary

In this exercise,  you have exercises various utility functions of Prototype JavaScript library.

                                                                                                                        return to the top



Exercise 2: Modify ajax-validation project to use Prototype's Ajax.Request


In this exercise, you are going to modify the ajax-validation project you have worked to use Prototype's Ajax.Requestion function.
  1. Open, build, and run "ajax-validation-p" sample application
  2. Modify index.jsp to use Prototype's Ajax.Request

(2.1) Open, build, and run "ajax-validation-p" sample application


In this step, you are going to open, build, and "ajax-validation-p" sample application.  This is the same ajax-validation sample application you've seen before.  This sample application already has prototype-1.4.0.js file included (but not using it yet).

1. Open ajax-validation-p NetBeans project. 

2 Build and run ajax-validation-p project.



(2.2) Modify index.jsp to use Prototype's Ajax.Request

In this step, you are going to modify index.jsp file to use Prototype's Ajax.Request instead of directly creating XMLHttpRequest JavaScript object and using it to perform asynchronous communication with the server.

1. Double-click index.jsp of the ajax-validation-p project to open it in the source editor window.
2. Modify the index.jsp file as following.  The new code fragments that need to be added are highlighted in bold and blue colored font while the old code fragments that need to be removed are highlighted in bold and red colored font.  The code fragments that remain the same are in regular font.  Please pay attention to the comments that explain why some code fragments are removed and why some are added.  (This is the complete code of the index.jsp file.  So you can copy and paste the complete code.)

<%-- Copyright 2005 Sun Microsystems, Inc. All rights reserved. You may not modify, use, reproduce, or distribute this software except in compliance with the terms of the License at: http://developer.sun.com/berkeley_license.html
$Id: index.jsp,v 1.4 2005/06/15 05:39:43 gmurray71 Exp $ --%>
<html>
    <head>

         <!-- Include Prototype library, make sure the directory path is set correctly -->
        <script language="JavaScript" type="text/javascript" src="prototype-1.4.0.js">
        </script>
       
        <script type="text/javascript">
            var req;
            var target;
            var isIE;
           
            /********************* Commented out *******************
            // (3) JavaScript function in which XMLHttpRequest JavaScript object is created.
            // Please note that depending on a browser type, you create
            // XMLHttpRequest JavaScript object differently.  Also the "url" parameter is not
            // used in this code (just in case you are wondering why it is
            // passed as a parameter).
            //
            function initRequest(url) {
                if (window.XMLHttpRequest) {
                    req = new XMLHttpRequest();
                } else if (window.ActiveXObject) {
                    isIE = true;
                    req = new ActiveXObject("Microsoft.XMLHTTP");
                }
            }

            // (2) Event handler that gets invoked whenever a user types a character
            // in the input form field whose id is set as "userid".  This event
            // handler invokes "initRequest(url)" function above to create XMLHttpRequest
            // JavaScript object.
            //

             * We don't need to do the low-level XMLHttpRequest handling anymore
             * since it is handled by dojo.io.bind().
            function validateUserId() {
                if (!target) target = document.getElementById("userid");
                var url = "validate?id=" + escape(target.value);
  
                // Invoke initRequest(url) to create XMLHttpRequest object
                initRequest(url);
   
                // The "processRequest" function is set as a callback function.
                // (Please note that, in JavaScript, functions are first-class objects: they
                // can be passed around as objects.  This is different from the way
                // methods are treated in Java programming language.)
                req.onreadystatechange = processRequest;
                req.open("GET", url, true);
                req.send(null);
            }
            **********************************************************/
           
            // This is the modified validateUserId() function
            function validateUserId() {
                if (!target) target = $("userid");
                var sampleFormNode = $("submit_btn");
   
                // Use Prototype's Ajax.Request for remoting
                var url = 'validate';
                var pars = "action=create&"+ "id=" + escape(target.value);
                   
                var myAjax = new Ajax.Request(
                                              url,
                                              {
                                                method: 'get',
                                                parameters: pars,
                                                onComplete: processRequest
                                              }
                                             );                       
           }

            // (4) Callback function that gets invoked asynchronously by the browser
            // when the data has been successfully returned from the server.
            // (Actually this callback function gets called every time the value
            // of "readyState" field of the XMLHttpRequest object gets changed.)
            // This callback function needs to be set to the "onreadystatechange"
            // field of the XMLHttpRequest.
            //
            /********************* commented out **************************************
            function processRequest() {
                if (req.readyState == 4) {
                  if (req.status == 200) {
       
                    // Extract "true" or "false" from the returned data from the server.
                    // The req.responseXML should contain either <valid>true</valid> or <valid>false</valid>
                    var message = req.responseXML.getElementsByTagName("valid")[0].childNodes[0].nodeValue;
           
                    // Call "setMessageUsingDOM(message)" function to display
                    // "Valid User Id" or "Invalid User Id" message.
                    setMessageUsingDOM(message);
           
                    // If the user entered value is not valid, do not allow the user to
                    // click submit button.
                    var submitBtn = document.getElementById("submit_btn");
                    if (message == "false") {
                        submitBtn.disabled = true;
                    } else {
                        submitBtn.disabled = false;
                    }
                  }
                }
            }
            *******************************************************************/
           
            // Modified processRequest(req) function.  Notice we do not have to check the readyState
            // and status fields of the XMLHttpRequest object.
            function processRequest(req) {
                var message = req.responseXML.getElementsByTagName("valid")[0].childNodes[0].nodeValue;
                setMessageUsingDOM(message);
                var submitBtn = $("submit_btn");
                if (message == "false") {
                    submitBtn.disabled = true;
                } else {
                    submitBtn.disabled = false;
                }
            }

            // This function is not used for now. You will use this later.
            //
            function setMessageUsingInline(message) {
                mdiv = document.getElementById("userIdMessage");
                if (message == "false") {
                    mdiv.innerHTML = "<div style=\"color:red\">Invalid User Id</div>";
                } else {
                    mdiv.innerHTML = "<div style=\"color:green\">Valid User Id</div>";
                } 
            }

            // (5) Function in which message indicating the validity of the data gets displayed
            // through the "userIdMessage" <div> element.
            //
            function setMessageUsingDOM(message) {
                // var userMessageElement = document.getElementById("userIdMessage");
                var userMessageElement = $("userIdMessage");
                var messageText;
                if (message == "false") {
                    userMessageElement.style.color = "red";
                    messageText = "Invalid User Id";
                } else {
                    userMessageElement.style.color = "green";
                    messageText = "Valid User Id";
                }
                 /*************  commented out **********************************
                var messageBody = document.createTextNode(messageText);
                // if the messageBody element has been created simple replace it otherwise
                // append the new element
                if (userMessageElement.childNodes[0]) {
                    userMessageElement.replaceChild(messageBody, userMessageElement.childNodes[0]);
                } else {
                    userMessageElement.appendChild(messageBody);
                }
                 *************************************************************/
                // Use innerHTML instead of raw DOM API
                userMessageElement.innerHTML = messageText;
            }

            function disableSubmitBtn() {
                // var submitBtn = document.getElementById("submit_btn");
                var submitBtn = $("submit_btn");
                submitBtn.disabled = true;
            }
        </script>
        <title>Form Data Validation using AJAX</title>
    </head>
    <body onload="disableSubmitBtn()">
 
        <h1>Form Data Validation using AJAX</h1>
        <hr/>
        <p>
            This example shows how you can use AJAX to do server-side form data validation without
            a page reload.
        </p>
        <p>
            In the form below enter a user id. By default the user ids &quot;greg&quot; and &quot;duke&quot;
            are taken. If you attempt to enter a user id that has been taken an error message will be
            displayed next to the form field and the &quot;Create Account&quot; button will be
            disabled. After entering a valid user id and selecting the &quot;Create Account&quot;
            button that user id  will be added to the list of user ids that are taken.
        </p>
 
        <form name="updateAccount" action="validate" method="post">
            <input type="hidden" name="action" value="create"/>
            <table border="0" cellpadding="5" cellspacing="0">
                <tr>
                    <td><b>User Id:</b></td>
                    <td>
                        <!-- (1) Input form field whose id is set as "userid" and "validateUserId()" function is
                        associated with the onkeyup event -->
                        <input    type="text"
                        size="20" 
                        id="userid"
                        name="id"
                        onkeyup="validateUserId()">
                    </td>
                    <!-- The "userIdMessage" div element specifies the location where input validation
                    message gets displayed. -->
                    <td>
                        <div id="userIdMessage"></div>
                    </td>
                </tr>
                <tr>
                    <td align="right" colspan="2">
                        <input id="submit_btn" type="Submit" value="Create Account">
                    </td>
                    <td></td>
                </tr>
            </table>
        </form>
    </body>
</html>
Code-2.20: Modified index.jsp

3. Right-click ajax-validation-p project and select Run Project.  The new project should behave in the same way ajax-validation project behaved.

Solution to Exercise 2


The solution to this exercise is provided in  <LAB_UNZIPPED_DIRECTORY>/ajaxprototype/samples/ajax-validation-prototype-solution.  You can just open the project and run it.

Summary

In this exercise, you have modified sample applications that use XMLHttpRequest  to use Ajax.Request from Prototype.


Homework exercise (for people who are taking Sang Shin's "AJAX online course")


1. The homework is to modify the ajax-hello project that you did as the Homework Exercise of the "AJAX Basics and Developement" as described below. 
2.  For those of you who did not have the ajax-hello project handy, it is provided as <LAB_UNZIPPED_DIRECTORY>/ajaxprototype/samples/ajax-hello .  (You might want to create a new project by copying the ajax-hello project. You can name the new project in any way you want but here I am going to call to call it as ajax-hello-prototype.)

3. Send the following files to ajaxhomework@sun.com with Subject as AJAXHomework-ajaxprototype.
4. Helpful hints

How to send questions/feedback's on this lab


Congratulations!  You have successfully finished the lab.  If you have anyquestions or  feedback's on this lab, please send them to handsonlabs-ajaxprototype@yahoogroups.com.  Thanks!

I am also looking for volunteers who can help others on this lab.  If you have a few spare cycles and willing to help others, please add yourself to the list by sending an email to handsonlabs-ajaxprototype-subscribe@yahoogroups.com