SlideShare a Scribd company logo
© 2009 Marty Hall




 The Prototype Framework
             yp
    Part I: Ajax Support
                                    (
                                    (Prototype 1.6 Version)
                                           yp             )
            Originals of Slides and Source Code for Examples:
       http://courses.coreservlets.com/Course-Materials/ajax.html
          p                                              j
                  Customized Java EE Training: http://courses.coreservlets.com/
  Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
   Developed and taught by well-known author and developer. At public venues or onsite at your location.




                                                                                                                © 2009 Marty Hall




 For live Ajax & GWT training, see training
courses at http://courses.coreservlets.com/.
          t htt //                l t       /
      Taught by the author of Core Servlets and JSP, More
     Servlets and JSP and this tutorial. Available at public
                  JSP,          tutorial
     venues, or customized versions can be held on-site at
                       your organization.
   •C
    Courses d
            developed and t
                l   d d taught b M t H ll
                            ht by Marty Hall
          – Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF 1.x & 2.0, Ajax, GWT, custom mix of topics
          – Ajax courses can concentrate on 1EE Training: http://courses.coreservlets.com/ or survey several
                   Customized Java library (jQuery, Prototype/Scriptaculous, Ext-JS, Dojo, Google Closure)
   • Courses developed and taught by coreservlets.com experts (edited by Marty)
  Servlets, JSP, JSF 1.x & JSFEJB3, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
          – Spring, Hibernate/JPA, 2.0, Ruby/Rails
   Developed and taught by well-known author and developer. At public venues or onsite at your location.
                                        Contact hall@coreservlets.com for details
Topics in This Section
    • Overview of Prototype
    • Installation and documentation
    • Ajax.Request
         – Basics
         – Options
    •   HTML lookup and insertion
    •   Ajax.Updater
    •   Ajax.PeriodicalUpdater
        Ajax PeriodicalUpdater
    •   Handling JSON Data
    •   Comparing Ajax support to other libraries
         – jQuery, Dojo, Ext-JS
5




                                                                                                    © 2009 Marty Hall




                                  Introduction

                         Customized Java EE Training: http://courses.coreservlets.com/
           Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
            Developed and taught by well-known author and developer. At public venues or onsite at your location.
Overview of Prototype
    • Ajax utilities
      – Ajax.Request, Ajax.Updater, Ajax.PeriodicalUpdater
      – Wraps response in Ajax.Response
           • Several new properties but especially responseJSON
                         properties,
    • General DOM utilities
      –   $() to find element
      –   $F() to get form value
      –   element.update() to put into innerHTML
      –   Many helpers in Element class
    • General utilites
      –E t i
       Extensions for Class, Function, Array, String
                  f Cl       F ti      A      St i

7




    Ajax Utilities
    • Ajax.Request
      – T k URL and options object (onSuccess and
        Takes         d    i      bj ( S            d
        parameters properties).
      – Calls URL, passes result (Ajax.Response) to onSuccess
    • Ajax.Updater
      – Takes id of result region and URL.
      – Invokes URL once and puts responseText in result region
    • Ajax.PeriodicalUpdater
      – Takes id of result region, URL, options object with
                             g ,      , p         j
        “frequency” property. Can call “stop” on updater later.
    • Ajax.Response
      – Passed to response handler functions
      – properties: responseText, responseXML, responseJSON
8
Downloading and Installation
     • Download
       – h //
         http://www.prototypejs.org/download
                             j     /d   l d
             • Download a single .js file (e.g., prototype-1.6.02.js)
                   – Recommend renaming to prototype.js to simplify later upgrades
             • Thi t t i l corresponds t P t t
               This tutorial        d to Prototype 1.6
                                                   16
     • Online API
       – http://www.prototypejs.org/api
            p       p     yp j g p
     • Tips and Tutorials
       – http://www.prototypejs.org/learn
     • B
       Browser C
               Compatibility
                    tibilit
       –   Firefox: 1.5 or later
       –   Internet Explorer: 6.0 or later (does not work in IE 5.5!)
       –   Safari: 2.0 or later
9
       –   Opera: 9.25 or later




     Industry Usage




           Approximately 40% of matches to “prototype and JavaScript” were false positives such as “build a
10         prototype with JavaScript”. So, discount the Prototype graph by about 40%.
© 2009 Marty Hall




                            Ajax.Request:
                            Ajax Request:
                               Basics

                       Customized Java EE Training: http://courses.coreservlets.com/
         Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
          Developed and taught by well-known author and developer. At public venues or onsite at your location.




     Ajax.Request: Basic Syntax
     • new Ajax.Request(relative-url, options)
       – C ll relative-url, wraps response i Aj R
         Calls l i       l                 in Ajax.Reponse,
         passes response to function specified in options
          • Note it is “new Ajax.Request(...)”, not “Ajax.Request(...)”
     • Options
       – An anonymous object
       – Most important property: onSuccess
     • Basic example
       – new Ajax.Request(
           "some-file.jsp",
                 fil j
           {onSuccess: someHandlerFunction});
                 – someHandlerFunction should take one argument of type
                   Ajax.Response.
                   Ajax Response
                 – It is automatically wrapped in anonymous function with local copy
                   of request object, so it is threadsafe.
12
Data-Centric Ajax with and
     without Toolkits
     • With basic JavaScript
       function getRequestObject() {
         if (window.XMLHttpRequest) {
           return(new XMLHttpRequest());
         } else if (window.ActiveXObject) {
           return(new ActiveXObject("Microsoft.XMLHTTP"));
         } else { return(null); }
       }
       function sendRequest() {
         var request = getRequestObject();
         request.onreadystatechange =
           function() { someFunct(request); };
         request.open("GET", "some-url", true);
         request.send(null);
       }
13




     Data-Centric Ajax with and
     without Toolkits
     • jQuery (handler passed response text)
       $.ajax({url: "address",
               success: handlerFunct});
     • Prototype (handler passed response object)
       new Ajax.Request("address",
                        {onSuccess: handlerFunct});
     • Ext (handler passed response object)
       Ext.Ajax.request({url: "address",
                         success: handlerFunct});
     • Dojo (handler passed response text)
       dojo.xhrGet({url: " dd
       d j   h G t({ l "address","
                    load: handlerFunct});
14
Ajax.Request Example Code:
      JavaScript
     function showTime1() {
       new Ajax.Request(
           Ajax Request(
         "show-time.jsp",
         { onSuccess: showAlert });
     }                              This i P t t
                                    Thi is a Prototype Ajax.Response object,
                                                       Aj R           bj t
                                    not the raw XmlHttpRequest.


     function showAlert(response) {
       alert(response.responseText);
     }




15




      Ajax.Request Example Code:
      HTML
     ...
     <head><title>Prototype and Ajax</title>...
                                Ajax</title>
     <script src="./scripts/prototype.js"
             type="text/javascript"></script>
     <script src="./scripts/prototype-examples.js"
                   /       /
             type="text/javascript"></script>
     </head>
     <body>...
     <fieldset>
       <legend>Ajax.Request: Basics</legend>
          g      j    q             / g
       <form action="#">
         <input type="button" value="Show Time"
                onclick= showTime1() />
                onclick='showTime1()'/>
       </form>
     </fieldset>
16
Ajax.Request Example Code:
     JSP
     It is now <%= new java.util.Date() %>




17




     Ajax.Request: Results




18
© 2009 Marty Hall




                Ajax.Request:
                Ajax Request:
              Passing Parameters
                    g

                       Customized Java EE Training: http://courses.coreservlets.com/
         Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
          Developed and taught by well-known author and developer. At public venues or onsite at your location.




     Ajax.Request Options
     { property1: v1 property2: v2 }
                  v1,           v2...}
     • The second arg is an anonymous object with these
       as the most important properties
       – onSuccess (default: none)
           • Response handler function (takes Ajax.Response as arg)
           • There are also many similar related options: onComplete
                                                          onComplete,
             onFailure, onException, onXYX (for HTTP status codes)
       – parameters (default: empty string)
           • Can be explicit parameter string: "p1=val1&p2=val2"
           • Can also be parameter object: {p1: val1, p2: val2}
                 – Values will be escaped automatically
       – asynchronous (default: true)
       – method (default: post)
       – evalJS (default: true)
           • Response text passed to “eval” if response type is
             application/javascript or a similar type
              pp         j       p                yp
       – evalJSON (default: true)
           • Response text passed to eval (with parens added) and sent to
20
             responseJSON if response type is application/json
Ajax.Request Parameters
     Example Code: JavaScript
     function showParams1() {
       new Ajax.Request(
           Ajax Request(
         "show-params.jsp",
         { onSuccess: showAlert,
           parameters: "param1=foo&param2=bar" });
     }

     function showAlert(response) {
       alert(response.responseText);
     }




21




     Ajax.Request Parameters
     Example Code: HTML and JSP
     <fieldset>
       <legend>Ajax.Request:
       <legend>Ajax Request:
                The 'parameters' Option</legend>
       <form action="#">
         <input type="button" value="Show Params"
                 onclick='showParams1()'/>
       </form>
     </fieldset>




22
Ajax.Request Parameters
     Example Code: HTML and JSP
     • HTML
     <fieldset>
       <legend>Ajax.Request:
                The 'parameters' Option</legend>
                     p            p        g
       <form action="#">
         <input type="button" value="Show Params"
                 onclick showParams1() />
                 onclick='showParams1()'/>
       </form>
     </fieldset>


     • JSP (show-params.jsp)
     param1 is ${param param1}
               ${param.param1},
     param2 is ${param.param2}.
23




     Ajax.Request Parameters: Results




24
Utilities for Reading and Writing
     HTML Elements
     • $("id")
       – Returns element with given id [getElementById("id")]
          • Can also take an Element instead of an element id
          • Can also take multiple arguments, in which case it returns
            an array of the Element results
          • Yes, “$” is really the function name
     • $F("id")
       $F( id )
       – Returns value of form element with given ID
          • Single value for most elements, array for multi-select lists
               g                              ,     y
          • For textfields, equivalent to $("id").value
     • update("html-string")
       – Inserts i
                 into innerHTML property
                      i
       – E.g., $("result-region").update("<h1>Test</h1>")
25




     Building Parameter Strings
     • The $F function does not escape values
       – S this could yield illegal results
         So, hi    ld i ld ill l        l
          • { onSuccess: someHandlerFunction,
              parameters: "param1=" + $F("field1") }
              – If field 1 contains spaces, ampersands, etc., this causes problems
                   fi ld      t i                   d     t thi              bl
              – You could do escape($F("field1")), but this gets a bit verbose
     • Instead of a parameter string, you can
       supply parameter object
            l         t   bj t
       – { param1: "val1", param2: "val2" ... }
       – Values (usually from $F(...)) are automatically escaped,
         then whole thing converted to parameter string
       – You can also do this explicitly anywhere with $H
         function that creates Hash, and toQueryString method
                               Hash
          • $H({p1: "val1", p2: "val2"}).toQueryString() returns
            "p1=val1&p2=val2"
26
Ajax.Request: Reading/Writing Utils
      Example Code: JavaScript
     function showParams2() {          Original (not escaped) value of textfield
                                       whose id (not name) is “field1”.
       var params =
         { param1: $F("field1"),
           param2: $F("field2") };
       new Ajax.Request(
         "show-params.jsp",
         { onSuccess: updateResult,
           parameters: params });
                                    Parameter object is converted
     }                              to parameter string with escaped values.



     function updateResult(response) {
       $("result1").update(response.responseText);
     }
                                                 Inserts into innerHTML property.
          Finds element whose id is "result1".

27




      Ajax.Request: Reading/Writing Utils
      Example Code: HTML
     <fieldset>
       <legend>Ajax.Request:
       <legend>Ajax Request:
                Reading/Writing Utilities</legend>
       <form action="#">
         param1:
         <input type="text" id="field1"/>
         <br/>
         param2:
         <input type="text" id="field2"/>
            /
         <br/>
         <input type="button" value="Show Params"
                 onclick='showParams2()'/>
         <h2 id="result1"></h2>
              id= result1 ></h2>
       </form>
     </fieldset>
28
Ajax.Request: Reading/Writing
     Utils: Results




29




                                                                                                © 2009 Marty Hall




                            Ajax.Updater

                     Customized Java EE Training: http://courses.coreservlets.com/
       Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
        Developed and taught by well-known author and developer. At public venues or onsite at your location.
Ajax.Updater: Basic Syntax
     • new Ajax.Updater(result-id, url, options)
        – Calls URL
        – Extracts resultText
        – Puts it into innerHTML of element with result-id
                                                 result id
     • Options
        – An anonymous object just as with Ajax.Request
                         object,           Ajax Request
        – Most important property: parameters
        – No onSuccess usually needed




31




      Content-Centric Ajax with and
      without Toolkits (Basic JS Only)
     function getRequestObject() { ... }

     function ajaxResult(address, resultRegion) {
       var request = getRequestObject();
       request.onreadystatechange =
         function() { showResponseText(request,
                                       resultRegion); };
       request.open("GET", address, true);
       request.send(null);
       request send(null);
     }

     function showResponseText(request, resultRegion) {
                     p        ( q     ,         g   )
       if ((request.readyState == 4) &&
           (request.status == 200)) {
         document.getElementById(resultRegion).innerHTML =
           request.responseText;
                 t         T t
       }
     }
32
Content-Centric Ajax with and
      without Toolkits (Ajax Request)
                       (Ajax.Request)
     function ajaxResult(address, resultRegion) {
       new Ajax Request(
           Ajax.Request(
         address,
         { onSuccess:
             function(response) {
               showResponseText(response, resultRegion);
             }
         });
     }

     function showResponseText(response, resultRegion) {
       u ct o s o espo se e t( espo se, esu t eg o )
        $(resultRegion).update(response.responseText);
     }



33




      Content-Centric Ajax with and
      without Toolkits (Libraries)
     • jQuery
        function ajaxResult(address, resultRegion) {
          $(resultRegion).load(address);
        }
     • Prototype
        function ajaxResult(address, resultRegion) {
          new Ajax.Updater(resultRegion, address);
               j    p     (        g   ,        );
        }
     • Dojo
        – No explicit support for content-centric Ajax
                l             f
     • Ext-JS
        function ajaxResult(address resultRegion) {
                 ajaxResult(address,
          Ext.get(resultRegion).load({ url: address});
        }
34
Ajax.Updater Example Code:
     JavaScript
     function showParams3() {
       var params =
         { param1: $F("param3"),
           param2: $F("param4") };
                                               id of element into whose innerHTML
       new Ajax.Updater(                       the responseText is inserted

         "result2",
         "show-params.jsp",
         { parameters: params });
     }

     • Notes
       – No onSuccess normally needed
       – Can update a single element only. If you need to update more, use
         Ajax.Request
         Ajax Request with onSuccess
          • You could also return script from server, but then server needs
            to know name of DOM elements
35




     Ajax.Updater Example Code:
     HTML
     <fieldset>
       <legend>Ajax.Updater</legend>
       <legend>Ajax Updater</legend>
       <form action="#">
         param1:
         <input type="text" id="param3"/>
                                        /
         <br/>
         param2:
         <input type="text" id="param4"/>
         <br/>
         <input type="button" value="Show Params"
            p     yp
                 onclick='showParams3()'/>
         <h2 id="result2"></h2>
       </form>
     </fieldset>
36
Ajax.Updater: Results




37




     Ajax.Updater Options
     • evalScripts
       – Should <script> tags in the response be evaluated?
       – Default is false, so this option is very important if you return
         <script> tags that set event handlers (e.g. for scriptaculous in-place
         editors) for elements that are inserted
                )
     • insertion
       – Where text should be inserted relative to what is already there.
       – Default is to replace any existing content.
       – Options are 'top', 'bottom', 'before', 'after'
     • Standard options still supported
       – parameters onSuccess, etc
         parameters, onSuccess etc.
     • Example
       – var params = { param1: "foo", param2: "bar" };
       – new Ajax Updater("some id", "some address",
              Ajax.Updater( some-id some-address
               { evalScripts: true, insertion: 'top', parameters: params });
38
© 2009 Marty Hall




         Ajax.PeriodicalUpdater
         Aj P i di lU d t

                       Customized Java EE Training: http://courses.coreservlets.com/
         Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
          Developed and taught by well-known author and developer. At public venues or onsite at your location.




     Ajax.PeriodicalUpdater Example
     Code: JavaScript
     var updater; // Save ref so can "stop" later

     function showTime2() {
       updater = new Ajax.PeriodicalUpdater(
         "result3",
         "show-time.jsp",
         { frequency: 5 });
     }




40
Ajax.PeriodicalUpdater Example
     Code: HTML
     <fieldset>
       <legend>Ajax.PeriodicalUpdater</legend>
       <legend>Ajax PeriodicalUpdater</legend>
       <form action="#">
          <h2 id="result3"></h2>
          <script type="text/javascript">
                            /
            showTime2();
          </script>
          <input type="button" value="Stop Updates"
                 onclick='updater.stop()'/>
        /
       </form>
     </fieldset>


     • Note
       – Form needed only if you want to let user stop the action
41




     Ajax.PeriodicalUpdater: Results




42
© 2009 Marty Hall




             Handling
             H dli JSON Data
                        D t

                       Customized Java EE Training: http://courses.coreservlets.com/
         Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
          Developed and taught by well-known author and developer. At public venues or onsite at your location.




     Ajax.Response Properties
     • The arg passed to response handler has
       these as most important properties
       – status, statusText
          • HTTP status code and corresponding text
       – responseText
          • Same as normal XmlHttpRequest.responseText
       – responseXML
          espo se
          • Same as normal XmlHttpRequest.responseXML
       – responseJSON
          • Response text wrapped in parens and passed to "eval"eval
          • Only available if response type is application/json
       – headerJSON
          • Evaluated content of X-JSON response header
          • Alternative for responseJSON for small amounts of data
44
Ajax.Response Methods
     • Can also call these methods on response
       – getHeader(responseHeaderName)
          • Gets header value.
          • Does not throw exception if header missing (unlike native
            XmlHttpResponse method)
       – getAllHeaders()
          • Returns a string with all headers delimited by newlines
                                      headers,
          • Does not throw exception if there are no headers
       – getResponseHeader, getAllResponseHeaders
          • Native version of above methods
          • Throws exceptions if headers missing
          • Used only with preexisting code that handled exeptions.
                     y     p         g                      p
            Use getHeader and getAllHeaders otherwise

45




     Using JSON Data with
     responseJSON property
     • Response object properties
       – responseText, responseXML, and responseJSON
       – Response object passed to handler function (designated
         with onSuccess, etc )
              onSuccess etc.)
       – For more details see Ajax.Response in online API
     • Behavior
       – Response text wrapped in parens and passed to "eval"
          • Server returns { prop1: val1, prop2: val2 } without parens
     • R
       Requirements
           i     t
       – responseJSON populated only if response type is
         application/json

46
responseJSON Example Code:
     Core JavaScript
     function showNums() {
       new Ajax.Request(
           Ajax Request(
         "show-nums",
         { onSuccess: showNumberList,    Strings

           method: "get" });
     }

     function showNumberList(response) {
       var obj = response.responseJSON;
       var list = makeList(obj.fg, obj.bg,
                          ( j g,     j g,
                           obj.fontSize, obj.numbers);
       $("result4").update(list);
     }
                                          Array of doubles
                             Integer


47




     responseJSON Example Code:
     Auxiliary JavaScript
     function makeList(fg, bg, fontSize, nums) {
       return(
         listStartTags(fg, bg, fontSize) +
         listItems(nums) +
         listEndTags());
     }

     function li tSt tT
     f   ti   listStartTags(fg, b
                           (f   bg, f tSi ) {
                                    fontSize)
       return(
         "<div style='color:" + fg + "; " +
                     "background-color:" + bg + "; " +
                     "font-size:" + fontSize + "px'>n" +
         "<ul>n");
     }

48
responseJSON Example Code:
     Auxiliary JavaScript (Continued)
     function listItems(items) {
       var result = "";;
       for(var i=0; i<items.length; i++) {
         result = result + "<li>" + items[i] + "</li>n";
       }
       return(result);
     }

     function listEndTags() {
       return("</ul></div>");
     }




49




     responseJSON Example Code:
     HTML
     <fieldset>
       <legend>Ajax.Request:
       <legend>Ajax Request: responseJSON</legend>
       <form action="#">
         <input type="button" value="Show Nums"
                onclick='showNums()'/>
                                    /
         <div id="result4"></div>
       </form>
     </fieldset>




50
responseJSON Example Code:
      Servlet
     public class ShowNumbers extends HttpServlet {
       public void doGet(HttpServletRequest request,
                         HttpServletResponse response)
           throws ServletException, IOException {
         response.setHeader("Cache-Control", "no-cache");
         response.setHeader("Pragma", "no-cache");
            p              (    g   ,           )
         String fg = ColorUtils.randomColor();
         request.setAttribute("fg", fg);
         String bg = ColorUtils.randomColor();
         request.setAttribute( bg ,
         request.setAttribute("bg", bg);
         String fontSize = "" + (10 + ColorUtils.randomInt(30));
         request.setAttribute("fontSize", fontSize);
         double[] nums =
           { Math random() Math random() Math random() };
             Math.random(), Math.random(), Math.random()
         request.setAttribute("nums", nums);
         response.setContentType("application/json");
         String outputPage = "/WEB-INF/results/show-nums.jsp";
         RequestDispatcher dispatcher =
           request.getRequestDispatcher(outputPage);
         dispatcher.include(request, response);
51
     }}




      responseJSON Example Code: JSP
     { fg: "${fg}",
       bg: "${b }"
       b   "${bg}",
       fontSize: ${fontSize},
       numbers: [ ${nums[0]}, ${nums[1]}, ${nums[2]}]
                    {   [ ]}, {     [ ]}, {     [ ]}]
     }

     • Notes
        – Client-side code does not need wrap in parens and pass to
          “eval”. JSON evaluation handled automatically by
           eval .
          Prototype
        – Types
           • f and b St i
             fg d bg: Strings
           • fontSize: int
52         • numbers: Array of doubles
JSON Example Code: Auxiliary
         Java Code
     public class ColorUtils {
       p
       private static String[] colors = {
                           g[]
         "aqua", "black", "blue", "fuchsia", "gray",
         "green", "lime", "maroon", "navy", "olive",
         "purple", "red", "silver", "teal", "white", "yellow"
       };

         /** One of the official HTML color names, at random. */

         public static String randomColor() {
           return(RandomUtils.randomElement(colors));
         }

         private ColorUtils() {}   // Uninstantiatable class}
     }




53




         JSON Example Code: Auxiliary
         Java Code
     public class RandomUtils {
       private static Random r = new Random();

         public static int randomInt(int range) {
           return(r.nextInt(range));
           return(r nextInt(range));
         }

         public static int randomIndex(Object[] array) {
           return(randomInt(array.length));
         }

         public static <T> T randomElement(T[] array) {
           return(array[randomIndex(array)]);
         }
     }

54
responseJSON Example:
     Results




55




                                                                                                © 2009 Marty Hall




                                       Wrap-up

                     Customized Java EE Training: http://courses.coreservlets.com/
       Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
        Developed and taught by well-known author and developer. At public venues or onsite at your location.
“Best” JavaScript Libraries
                     p
     • General JS programming                 • Traditional Ajax support
      – Leader: Prototype                      – Tie
     • Other programming (Java) • Server communication
      – Leader (only): GWT                     – Leader: GWT
     • DOM manipulation                        – 2nd tier: DWR, JSON-RPC
      – Leader: jQuery                        • Usage in industry
        • Oth copying jQuery approach and
          Others        i jQ            h d    – Leader: jQuery
          closing gap. jQuery released CSS
          matching library separately          – 2nd tier: Ext-JS, Dojo, YUI,
          (http://sizzlejs.com)                  Prototype, Scriptaculous, GWT
     • Rich GUIs                              • Looking ahead
      – Leaders: Ext-JS, YUI, Dojo             – All these entries are likely to
      – 2nd tier: jQuery UI GWT
                         UI,                     c ge s g c
                                                 change significantlyy
                                               – Lurking on the horizon:
     • Familiarity to JS developers              Google “Closure” library
57    – Lowest: GWT




      Recommended Books
     • Prototype and script.aculo.us: You Never
       Knew J
       K     JavaScript C ld Do Thi !
                 S i Could D This!
        – By Christophe Porteneuve
     • Prototype and Scriptaculous in Action
        – By Dave Crane, Bear Bebeault, Tom Locke




58
Summary
     • Ajax.Request
        – new Aj R
              Ajax.Request("url", { onSuccess: h dl ... })
                          (" l"       S        handler, });
            • Also has parameters option (string or object)
            • Don't forget the “new”"
     • Ajax.Updater
        – new Ajax.Updater("id", "url", {options});
     • Ajax.PeriodicalUpdater
        – new Ajax.PeriodicalUpdater("id", "url", { frequency: ...});
     • Ajax.Response
        – Has responseJSON property
                       SO
     • Utility function
        – $("some-id")  Element with that id
           (         )
        – $F("some-id")  Value of Element with that id
        – someElement.update("html") – inserts in innerHTML
59




                                                                                                   © 2009 Marty Hall




                                   Questions?

                        Customized Java EE Training: http://courses.coreservlets.com/
          Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
           Developed and taught by well-known author and developer. At public venues or onsite at your location.

More Related Content

PDF
Automatically generating-json-from-java-objects-java-objects268
PDF
Ajax basics
PDF
Sling Models Using Sightly and JSP by Deepak Khetawat
PDF
Lazy vs. Eager Loading Strategies in JPA 2.1
PDF
Ajax Basics 2
PDF
Ajax Basics 1
PPT
55 New Features in Java 7
PPTX
Mastering the Sling Rewriter
Automatically generating-json-from-java-objects-java-objects268
Ajax basics
Sling Models Using Sightly and JSP by Deepak Khetawat
Lazy vs. Eager Loading Strategies in JPA 2.1
Ajax Basics 2
Ajax Basics 1
55 New Features in Java 7
Mastering the Sling Rewriter

What's hot (20)

PPTX
AEM and Sling
PDF
Ajax tutorial
PDF
13 java beans
PPTX
JShell: An Interactive Shell for the Java Platform
PPTX
Interactive Java Support to your tool -- The JShell API and Architecture
KEY
Django In The Real World
PPT
Building a java tracer
PPT
Practical JRuby
PDF
Creating Dynamic Charts With JFreeChart
PPTX
Mastering Java Bytecode - JAX.de 2012
PPTX
Content Modeling Behavior
PPTX
Building a Unified Data Pipline in Spark / Apache Sparkを用いたBig Dataパイプラインの統一
PPTX
The CoFX Data Model
PDF
Tweet4Beer (atualizada): Torneira de Chopp Controlada por Java, JavaFX, IoT ...
PPTX
Software Uni Conf October 2014
PPTX
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
PPTX
Getting started with Java 9 modules
PPTX
Integration patterns in AEM 6
PDF
Solid And Sustainable Development in Scala
PPTX
Why Doesn't Java Has Instant Turnaround - Con-FESS 2012
AEM and Sling
Ajax tutorial
13 java beans
JShell: An Interactive Shell for the Java Platform
Interactive Java Support to your tool -- The JShell API and Architecture
Django In The Real World
Building a java tracer
Practical JRuby
Creating Dynamic Charts With JFreeChart
Mastering Java Bytecode - JAX.de 2012
Content Modeling Behavior
Building a Unified Data Pipline in Spark / Apache Sparkを用いたBig Dataパイプラインの統一
The CoFX Data Model
Tweet4Beer (atualizada): Torneira de Chopp Controlada por Java, JavaFX, IoT ...
Software Uni Conf October 2014
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Getting started with Java 9 modules
Integration patterns in AEM 6
Solid And Sustainable Development in Scala
Why Doesn't Java Has Instant Turnaround - Con-FESS 2012
Ad

Viewers also liked (6)

PDF
69-kauri
PDF
11-DWR-and-JQuery
PDF
neurisa_11_09_rosenthal
PDF
RichFacesWhatIsNewIn330
PDF
manual-en
PDF
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
69-kauri
11-DWR-and-JQuery
neurisa_11_09_rosenthal
RichFacesWhatIsNewIn330
manual-en
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
Ad

Similar to Prototype-1 (20)

PDF
Ajax Tags Advanced
PDF
jQuery-1-Ajax
PDF
&lt;img src="../i/r_14.png" />
PDF
jQuery-1-Ajax
PDF
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
PDF
JavaScript-Core
PDF
JavaScript-Core
PDF
Json generation
PDF
02 servlet-basics
PDF
15 expression-language
PDF
Java script core
PDF
14 mvc
PDF
java beans
PDF
03 form-data
PDF
Jersey and JAX-RS
PDF
Iasi code camp 12 october 2013 jax-rs-jee-ecosystem - catalin mihalache
PPT
Introduction to Javascript
PDF
01 overview-and-setup
PDF
Building Applications Using Ajax
PDF
10 jsp-scripting-elements
Ajax Tags Advanced
jQuery-1-Ajax
&lt;img src="../i/r_14.png" />
jQuery-1-Ajax
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
JavaScript-Core
JavaScript-Core
Json generation
02 servlet-basics
15 expression-language
Java script core
14 mvc
java beans
03 form-data
Jersey and JAX-RS
Iasi code camp 12 october 2013 jax-rs-jee-ecosystem - catalin mihalache
Introduction to Javascript
01 overview-and-setup
Building Applications Using Ajax
10 jsp-scripting-elements

More from tutorialsruby (20)

PDF
&lt;img src="../i/r_14.png" />
PDF
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
PDF
&lt;img src="../i/r_14.png" />
PDF
&lt;img src="../i/r_14.png" />
PDF
Standardization and Knowledge Transfer – INS0
PDF
xhtml_basics
PDF
xhtml_basics
PDF
xhtml-documentation
PDF
xhtml-documentation
PDF
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
PDF
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
PDF
HowTo_CSS
PDF
HowTo_CSS
PDF
BloggingWithStyle_2008
PDF
BloggingWithStyle_2008
PDF
cascadingstylesheets
PDF
cascadingstylesheets
PDF
Winter%200405%20-%20Advanced%20Javascript
&lt;img src="../i/r_14.png" />
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
Standardization and Knowledge Transfer – INS0
xhtml_basics
xhtml_basics
xhtml-documentation
xhtml-documentation
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
HowTo_CSS
HowTo_CSS
BloggingWithStyle_2008
BloggingWithStyle_2008
cascadingstylesheets
cascadingstylesheets
Winter%200405%20-%20Advanced%20Javascript

Recently uploaded (20)

PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
A Presentation on Artificial Intelligence
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Encapsulation theory and applications.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Approach and Philosophy of On baking technology
PPTX
Big Data Technologies - Introduction.pptx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Unlocking AI with Model Context Protocol (MCP)
PPT
Teaching material agriculture food technology
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Building Integrated photovoltaic BIPV_UPV.pdf
A Presentation on Artificial Intelligence
Dropbox Q2 2025 Financial Results & Investor Presentation
Encapsulation theory and applications.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Approach and Philosophy of On baking technology
Big Data Technologies - Introduction.pptx
Review of recent advances in non-invasive hemoglobin estimation
Reach Out and Touch Someone: Haptics and Empathic Computing
Unlocking AI with Model Context Protocol (MCP)
Teaching material agriculture food technology
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
20250228 LYD VKU AI Blended-Learning.pptx
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Per capita expenditure prediction using model stacking based on satellite ima...
MYSQL Presentation for SQL database connectivity
Agricultural_Statistics_at_a_Glance_2022_0.pdf

Prototype-1

  • 1. © 2009 Marty Hall The Prototype Framework yp Part I: Ajax Support ( (Prototype 1.6 Version) yp ) Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/Course-Materials/ajax.html p j Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. © 2009 Marty Hall For live Ajax & GWT training, see training courses at http://courses.coreservlets.com/. t htt // l t / Taught by the author of Core Servlets and JSP, More Servlets and JSP and this tutorial. Available at public JSP, tutorial venues, or customized versions can be held on-site at your organization. •C Courses d developed and t l d d taught b M t H ll ht by Marty Hall – Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF 1.x & 2.0, Ajax, GWT, custom mix of topics – Ajax courses can concentrate on 1EE Training: http://courses.coreservlets.com/ or survey several Customized Java library (jQuery, Prototype/Scriptaculous, Ext-JS, Dojo, Google Closure) • Courses developed and taught by coreservlets.com experts (edited by Marty) Servlets, JSP, JSF 1.x & JSFEJB3, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. – Spring, Hibernate/JPA, 2.0, Ruby/Rails Developed and taught by well-known author and developer. At public venues or onsite at your location. Contact hall@coreservlets.com for details
  • 2. Topics in This Section • Overview of Prototype • Installation and documentation • Ajax.Request – Basics – Options • HTML lookup and insertion • Ajax.Updater • Ajax.PeriodicalUpdater Ajax PeriodicalUpdater • Handling JSON Data • Comparing Ajax support to other libraries – jQuery, Dojo, Ext-JS 5 © 2009 Marty Hall Introduction Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.
  • 3. Overview of Prototype • Ajax utilities – Ajax.Request, Ajax.Updater, Ajax.PeriodicalUpdater – Wraps response in Ajax.Response • Several new properties but especially responseJSON properties, • General DOM utilities – $() to find element – $F() to get form value – element.update() to put into innerHTML – Many helpers in Element class • General utilites –E t i Extensions for Class, Function, Array, String f Cl F ti A St i 7 Ajax Utilities • Ajax.Request – T k URL and options object (onSuccess and Takes d i bj ( S d parameters properties). – Calls URL, passes result (Ajax.Response) to onSuccess • Ajax.Updater – Takes id of result region and URL. – Invokes URL once and puts responseText in result region • Ajax.PeriodicalUpdater – Takes id of result region, URL, options object with g , , p j “frequency” property. Can call “stop” on updater later. • Ajax.Response – Passed to response handler functions – properties: responseText, responseXML, responseJSON 8
  • 4. Downloading and Installation • Download – h // http://www.prototypejs.org/download j /d l d • Download a single .js file (e.g., prototype-1.6.02.js) – Recommend renaming to prototype.js to simplify later upgrades • Thi t t i l corresponds t P t t This tutorial d to Prototype 1.6 16 • Online API – http://www.prototypejs.org/api p p yp j g p • Tips and Tutorials – http://www.prototypejs.org/learn • B Browser C Compatibility tibilit – Firefox: 1.5 or later – Internet Explorer: 6.0 or later (does not work in IE 5.5!) – Safari: 2.0 or later 9 – Opera: 9.25 or later Industry Usage Approximately 40% of matches to “prototype and JavaScript” were false positives such as “build a 10 prototype with JavaScript”. So, discount the Prototype graph by about 40%.
  • 5. © 2009 Marty Hall Ajax.Request: Ajax Request: Basics Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Ajax.Request: Basic Syntax • new Ajax.Request(relative-url, options) – C ll relative-url, wraps response i Aj R Calls l i l in Ajax.Reponse, passes response to function specified in options • Note it is “new Ajax.Request(...)”, not “Ajax.Request(...)” • Options – An anonymous object – Most important property: onSuccess • Basic example – new Ajax.Request( "some-file.jsp", fil j {onSuccess: someHandlerFunction}); – someHandlerFunction should take one argument of type Ajax.Response. Ajax Response – It is automatically wrapped in anonymous function with local copy of request object, so it is threadsafe. 12
  • 6. Data-Centric Ajax with and without Toolkits • With basic JavaScript function getRequestObject() { if (window.XMLHttpRequest) { return(new XMLHttpRequest()); } else if (window.ActiveXObject) { return(new ActiveXObject("Microsoft.XMLHTTP")); } else { return(null); } } function sendRequest() { var request = getRequestObject(); request.onreadystatechange = function() { someFunct(request); }; request.open("GET", "some-url", true); request.send(null); } 13 Data-Centric Ajax with and without Toolkits • jQuery (handler passed response text) $.ajax({url: "address", success: handlerFunct}); • Prototype (handler passed response object) new Ajax.Request("address", {onSuccess: handlerFunct}); • Ext (handler passed response object) Ext.Ajax.request({url: "address", success: handlerFunct}); • Dojo (handler passed response text) dojo.xhrGet({url: " dd d j h G t({ l "address"," load: handlerFunct}); 14
  • 7. Ajax.Request Example Code: JavaScript function showTime1() { new Ajax.Request( Ajax Request( "show-time.jsp", { onSuccess: showAlert }); } This i P t t Thi is a Prototype Ajax.Response object, Aj R bj t not the raw XmlHttpRequest. function showAlert(response) { alert(response.responseText); } 15 Ajax.Request Example Code: HTML ... <head><title>Prototype and Ajax</title>... Ajax</title> <script src="./scripts/prototype.js" type="text/javascript"></script> <script src="./scripts/prototype-examples.js" / / type="text/javascript"></script> </head> <body>... <fieldset> <legend>Ajax.Request: Basics</legend> g j q / g <form action="#"> <input type="button" value="Show Time" onclick= showTime1() /> onclick='showTime1()'/> </form> </fieldset> 16
  • 8. Ajax.Request Example Code: JSP It is now <%= new java.util.Date() %> 17 Ajax.Request: Results 18
  • 9. © 2009 Marty Hall Ajax.Request: Ajax Request: Passing Parameters g Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Ajax.Request Options { property1: v1 property2: v2 } v1, v2...} • The second arg is an anonymous object with these as the most important properties – onSuccess (default: none) • Response handler function (takes Ajax.Response as arg) • There are also many similar related options: onComplete onComplete, onFailure, onException, onXYX (for HTTP status codes) – parameters (default: empty string) • Can be explicit parameter string: "p1=val1&p2=val2" • Can also be parameter object: {p1: val1, p2: val2} – Values will be escaped automatically – asynchronous (default: true) – method (default: post) – evalJS (default: true) • Response text passed to “eval” if response type is application/javascript or a similar type pp j p yp – evalJSON (default: true) • Response text passed to eval (with parens added) and sent to 20 responseJSON if response type is application/json
  • 10. Ajax.Request Parameters Example Code: JavaScript function showParams1() { new Ajax.Request( Ajax Request( "show-params.jsp", { onSuccess: showAlert, parameters: "param1=foo&param2=bar" }); } function showAlert(response) { alert(response.responseText); } 21 Ajax.Request Parameters Example Code: HTML and JSP <fieldset> <legend>Ajax.Request: <legend>Ajax Request: The 'parameters' Option</legend> <form action="#"> <input type="button" value="Show Params" onclick='showParams1()'/> </form> </fieldset> 22
  • 11. Ajax.Request Parameters Example Code: HTML and JSP • HTML <fieldset> <legend>Ajax.Request: The 'parameters' Option</legend> p p g <form action="#"> <input type="button" value="Show Params" onclick showParams1() /> onclick='showParams1()'/> </form> </fieldset> • JSP (show-params.jsp) param1 is ${param param1} ${param.param1}, param2 is ${param.param2}. 23 Ajax.Request Parameters: Results 24
  • 12. Utilities for Reading and Writing HTML Elements • $("id") – Returns element with given id [getElementById("id")] • Can also take an Element instead of an element id • Can also take multiple arguments, in which case it returns an array of the Element results • Yes, “$” is really the function name • $F("id") $F( id ) – Returns value of form element with given ID • Single value for most elements, array for multi-select lists g , y • For textfields, equivalent to $("id").value • update("html-string") – Inserts i into innerHTML property i – E.g., $("result-region").update("<h1>Test</h1>") 25 Building Parameter Strings • The $F function does not escape values – S this could yield illegal results So, hi ld i ld ill l l • { onSuccess: someHandlerFunction, parameters: "param1=" + $F("field1") } – If field 1 contains spaces, ampersands, etc., this causes problems fi ld t i d t thi bl – You could do escape($F("field1")), but this gets a bit verbose • Instead of a parameter string, you can supply parameter object l t bj t – { param1: "val1", param2: "val2" ... } – Values (usually from $F(...)) are automatically escaped, then whole thing converted to parameter string – You can also do this explicitly anywhere with $H function that creates Hash, and toQueryString method Hash • $H({p1: "val1", p2: "val2"}).toQueryString() returns "p1=val1&p2=val2" 26
  • 13. Ajax.Request: Reading/Writing Utils Example Code: JavaScript function showParams2() { Original (not escaped) value of textfield whose id (not name) is “field1”. var params = { param1: $F("field1"), param2: $F("field2") }; new Ajax.Request( "show-params.jsp", { onSuccess: updateResult, parameters: params }); Parameter object is converted } to parameter string with escaped values. function updateResult(response) { $("result1").update(response.responseText); } Inserts into innerHTML property. Finds element whose id is "result1". 27 Ajax.Request: Reading/Writing Utils Example Code: HTML <fieldset> <legend>Ajax.Request: <legend>Ajax Request: Reading/Writing Utilities</legend> <form action="#"> param1: <input type="text" id="field1"/> <br/> param2: <input type="text" id="field2"/> / <br/> <input type="button" value="Show Params" onclick='showParams2()'/> <h2 id="result1"></h2> id= result1 ></h2> </form> </fieldset> 28
  • 14. Ajax.Request: Reading/Writing Utils: Results 29 © 2009 Marty Hall Ajax.Updater Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.
  • 15. Ajax.Updater: Basic Syntax • new Ajax.Updater(result-id, url, options) – Calls URL – Extracts resultText – Puts it into innerHTML of element with result-id result id • Options – An anonymous object just as with Ajax.Request object, Ajax Request – Most important property: parameters – No onSuccess usually needed 31 Content-Centric Ajax with and without Toolkits (Basic JS Only) function getRequestObject() { ... } function ajaxResult(address, resultRegion) { var request = getRequestObject(); request.onreadystatechange = function() { showResponseText(request, resultRegion); }; request.open("GET", address, true); request.send(null); request send(null); } function showResponseText(request, resultRegion) { p ( q , g ) if ((request.readyState == 4) && (request.status == 200)) { document.getElementById(resultRegion).innerHTML = request.responseText; t T t } } 32
  • 16. Content-Centric Ajax with and without Toolkits (Ajax Request) (Ajax.Request) function ajaxResult(address, resultRegion) { new Ajax Request( Ajax.Request( address, { onSuccess: function(response) { showResponseText(response, resultRegion); } }); } function showResponseText(response, resultRegion) { u ct o s o espo se e t( espo se, esu t eg o ) $(resultRegion).update(response.responseText); } 33 Content-Centric Ajax with and without Toolkits (Libraries) • jQuery function ajaxResult(address, resultRegion) { $(resultRegion).load(address); } • Prototype function ajaxResult(address, resultRegion) { new Ajax.Updater(resultRegion, address); j p ( g , ); } • Dojo – No explicit support for content-centric Ajax l f • Ext-JS function ajaxResult(address resultRegion) { ajaxResult(address, Ext.get(resultRegion).load({ url: address}); } 34
  • 17. Ajax.Updater Example Code: JavaScript function showParams3() { var params = { param1: $F("param3"), param2: $F("param4") }; id of element into whose innerHTML new Ajax.Updater( the responseText is inserted "result2", "show-params.jsp", { parameters: params }); } • Notes – No onSuccess normally needed – Can update a single element only. If you need to update more, use Ajax.Request Ajax Request with onSuccess • You could also return script from server, but then server needs to know name of DOM elements 35 Ajax.Updater Example Code: HTML <fieldset> <legend>Ajax.Updater</legend> <legend>Ajax Updater</legend> <form action="#"> param1: <input type="text" id="param3"/> / <br/> param2: <input type="text" id="param4"/> <br/> <input type="button" value="Show Params" p yp onclick='showParams3()'/> <h2 id="result2"></h2> </form> </fieldset> 36
  • 18. Ajax.Updater: Results 37 Ajax.Updater Options • evalScripts – Should <script> tags in the response be evaluated? – Default is false, so this option is very important if you return <script> tags that set event handlers (e.g. for scriptaculous in-place editors) for elements that are inserted ) • insertion – Where text should be inserted relative to what is already there. – Default is to replace any existing content. – Options are 'top', 'bottom', 'before', 'after' • Standard options still supported – parameters onSuccess, etc parameters, onSuccess etc. • Example – var params = { param1: "foo", param2: "bar" }; – new Ajax Updater("some id", "some address", Ajax.Updater( some-id some-address { evalScripts: true, insertion: 'top', parameters: params }); 38
  • 19. © 2009 Marty Hall Ajax.PeriodicalUpdater Aj P i di lU d t Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Ajax.PeriodicalUpdater Example Code: JavaScript var updater; // Save ref so can "stop" later function showTime2() { updater = new Ajax.PeriodicalUpdater( "result3", "show-time.jsp", { frequency: 5 }); } 40
  • 20. Ajax.PeriodicalUpdater Example Code: HTML <fieldset> <legend>Ajax.PeriodicalUpdater</legend> <legend>Ajax PeriodicalUpdater</legend> <form action="#"> <h2 id="result3"></h2> <script type="text/javascript"> / showTime2(); </script> <input type="button" value="Stop Updates" onclick='updater.stop()'/> / </form> </fieldset> • Note – Form needed only if you want to let user stop the action 41 Ajax.PeriodicalUpdater: Results 42
  • 21. © 2009 Marty Hall Handling H dli JSON Data D t Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Ajax.Response Properties • The arg passed to response handler has these as most important properties – status, statusText • HTTP status code and corresponding text – responseText • Same as normal XmlHttpRequest.responseText – responseXML espo se • Same as normal XmlHttpRequest.responseXML – responseJSON • Response text wrapped in parens and passed to "eval"eval • Only available if response type is application/json – headerJSON • Evaluated content of X-JSON response header • Alternative for responseJSON for small amounts of data 44
  • 22. Ajax.Response Methods • Can also call these methods on response – getHeader(responseHeaderName) • Gets header value. • Does not throw exception if header missing (unlike native XmlHttpResponse method) – getAllHeaders() • Returns a string with all headers delimited by newlines headers, • Does not throw exception if there are no headers – getResponseHeader, getAllResponseHeaders • Native version of above methods • Throws exceptions if headers missing • Used only with preexisting code that handled exeptions. y p g p Use getHeader and getAllHeaders otherwise 45 Using JSON Data with responseJSON property • Response object properties – responseText, responseXML, and responseJSON – Response object passed to handler function (designated with onSuccess, etc ) onSuccess etc.) – For more details see Ajax.Response in online API • Behavior – Response text wrapped in parens and passed to "eval" • Server returns { prop1: val1, prop2: val2 } without parens • R Requirements i t – responseJSON populated only if response type is application/json 46
  • 23. responseJSON Example Code: Core JavaScript function showNums() { new Ajax.Request( Ajax Request( "show-nums", { onSuccess: showNumberList, Strings method: "get" }); } function showNumberList(response) { var obj = response.responseJSON; var list = makeList(obj.fg, obj.bg, ( j g, j g, obj.fontSize, obj.numbers); $("result4").update(list); } Array of doubles Integer 47 responseJSON Example Code: Auxiliary JavaScript function makeList(fg, bg, fontSize, nums) { return( listStartTags(fg, bg, fontSize) + listItems(nums) + listEndTags()); } function li tSt tT f ti listStartTags(fg, b (f bg, f tSi ) { fontSize) return( "<div style='color:" + fg + "; " + "background-color:" + bg + "; " + "font-size:" + fontSize + "px'>n" + "<ul>n"); } 48
  • 24. responseJSON Example Code: Auxiliary JavaScript (Continued) function listItems(items) { var result = "";; for(var i=0; i<items.length; i++) { result = result + "<li>" + items[i] + "</li>n"; } return(result); } function listEndTags() { return("</ul></div>"); } 49 responseJSON Example Code: HTML <fieldset> <legend>Ajax.Request: <legend>Ajax Request: responseJSON</legend> <form action="#"> <input type="button" value="Show Nums" onclick='showNums()'/> / <div id="result4"></div> </form> </fieldset> 50
  • 25. responseJSON Example Code: Servlet public class ShowNumbers extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); p ( g , ) String fg = ColorUtils.randomColor(); request.setAttribute("fg", fg); String bg = ColorUtils.randomColor(); request.setAttribute( bg , request.setAttribute("bg", bg); String fontSize = "" + (10 + ColorUtils.randomInt(30)); request.setAttribute("fontSize", fontSize); double[] nums = { Math random() Math random() Math random() }; Math.random(), Math.random(), Math.random() request.setAttribute("nums", nums); response.setContentType("application/json"); String outputPage = "/WEB-INF/results/show-nums.jsp"; RequestDispatcher dispatcher = request.getRequestDispatcher(outputPage); dispatcher.include(request, response); 51 }} responseJSON Example Code: JSP { fg: "${fg}", bg: "${b }" b "${bg}", fontSize: ${fontSize}, numbers: [ ${nums[0]}, ${nums[1]}, ${nums[2]}] { [ ]}, { [ ]}, { [ ]}] } • Notes – Client-side code does not need wrap in parens and pass to “eval”. JSON evaluation handled automatically by eval . Prototype – Types • f and b St i fg d bg: Strings • fontSize: int 52 • numbers: Array of doubles
  • 26. JSON Example Code: Auxiliary Java Code public class ColorUtils { p private static String[] colors = { g[] "aqua", "black", "blue", "fuchsia", "gray", "green", "lime", "maroon", "navy", "olive", "purple", "red", "silver", "teal", "white", "yellow" }; /** One of the official HTML color names, at random. */ public static String randomColor() { return(RandomUtils.randomElement(colors)); } private ColorUtils() {} // Uninstantiatable class} } 53 JSON Example Code: Auxiliary Java Code public class RandomUtils { private static Random r = new Random(); public static int randomInt(int range) { return(r.nextInt(range)); return(r nextInt(range)); } public static int randomIndex(Object[] array) { return(randomInt(array.length)); } public static <T> T randomElement(T[] array) { return(array[randomIndex(array)]); } } 54
  • 27. responseJSON Example: Results 55 © 2009 Marty Hall Wrap-up Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.
  • 28. “Best” JavaScript Libraries p • General JS programming • Traditional Ajax support – Leader: Prototype – Tie • Other programming (Java) • Server communication – Leader (only): GWT – Leader: GWT • DOM manipulation – 2nd tier: DWR, JSON-RPC – Leader: jQuery • Usage in industry • Oth copying jQuery approach and Others i jQ h d – Leader: jQuery closing gap. jQuery released CSS matching library separately – 2nd tier: Ext-JS, Dojo, YUI, (http://sizzlejs.com) Prototype, Scriptaculous, GWT • Rich GUIs • Looking ahead – Leaders: Ext-JS, YUI, Dojo – All these entries are likely to – 2nd tier: jQuery UI GWT UI, c ge s g c change significantlyy – Lurking on the horizon: • Familiarity to JS developers Google “Closure” library 57 – Lowest: GWT Recommended Books • Prototype and script.aculo.us: You Never Knew J K JavaScript C ld Do Thi ! S i Could D This! – By Christophe Porteneuve • Prototype and Scriptaculous in Action – By Dave Crane, Bear Bebeault, Tom Locke 58
  • 29. Summary • Ajax.Request – new Aj R Ajax.Request("url", { onSuccess: h dl ... }) (" l" S handler, }); • Also has parameters option (string or object) • Don't forget the “new”" • Ajax.Updater – new Ajax.Updater("id", "url", {options}); • Ajax.PeriodicalUpdater – new Ajax.PeriodicalUpdater("id", "url", { frequency: ...}); • Ajax.Response – Has responseJSON property SO • Utility function – $("some-id")  Element with that id ( ) – $F("some-id")  Value of Element with that id – someElement.update("html") – inserts in innerHTML 59 © 2009 Marty Hall Questions? Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.