SlideShare ist ein Scribd-Unternehmen logo
1 von 10
Downloaden Sie, um offline zu lesen
Rico AjaxEngine Tutorial

The Rico JavaScript library provides a single JavaScript object, AjaxEngine, for
adding Ajax to any HTML page.

What is Ajax?

Widkipedia has the following definition for Ajax:

Traditional web applications allow users to fill out forms, and when these forms are
submitted, a request is sent to a web server. The web server acts upon whatever
was sent by the form, and then responds back by sending a new web page. A lot of
bandwidth is wasted since much of the HTML from the first page is present in the
second page. Because a request to the web server has to be transmitted on every
interaction with the application, the application's response time is dependant on
the response time of the web server. This leads to user interfaces that are much
slower than their native counterparts.

AJAX applications, on the other hand, can send requests to the web server to
retrieve only the data that is needed, usually using SOAP or some other XML-based
web services dialect, and using JavaScript in the client to process the web server
response. The result is more responsive applications, since the amount of data
interchanged between the web browser and web server is vastly reduced. Web
server processing time is also saved, since a lot of this is done on the computer from
which the request came.

Comparing Ajax to Normal HTTP Mechanism
As stated above, the traditional way users interact with a page is to click a link
(usually translates to an HTTP GET request) or click a submit button on a form
                                                (usually translates to an HTTP POST
                   request                      request). In the first case, a new page
  Web Page                          Web
                                                is requested and the browser
     Web Page                      Server
                                                refreshes with new content. In the
                    response                    second case, either a new page or
                                                the same page with modified values
                                                is returned.

In Ajax the request is made using the JavaScript function XmlHttpRequest. The
request asks for a block of XML data (rather than a whole page to refresh) that the
JavaScript code can handle in whatever way it sees fit.


For example, here are some ways the XML data could be interpreted:
   • XML data that the JavaScript code parses to extract data. This data in
     turn is used to fill in field values or tables in a display.



                                                                                      1
Rico AjaxEngine Tutorial

   • XML data that the JavaScript runs an XSLT process on to convert into
     HTML code to be inserted on the page somewhere
   • XML data that holds JavaScript that the JavaScript code evaluates to
     issue commands
   • XML data that contains HTML code that can be placed inside another
     HTML element on the page

This list is not exhaustive. The point is – Ajax allows you to make a server
side call outside of the normal page refresh cycle. The data that is returned
can be defined in any manner that XML allows and the way it is interpreted
is open to the application’s determined usage of this data.

Rico AjaxEngine

Rico provides a JavaScript object named AjaxEngine that simplifies using Ajax to
update the contents within a page.

The engine provides the following features:
   • A standard XML definition for the basic Ajax response
   • A way to specify that a response is targeted for a specific HTML element
   • Automatic update of the targeted HTML element’s innerHTML with the
      contents of the response
   • A way to specify that a response is targeted for a specific JavaScript Ajax
      response handler
   • Standard mechanism for an Ajax response handler to receive response
      messages
   • Support for multiple Ajax responses as the result of one Ajax request
      (multiple updates to elements and/or JavaScript objects).
   • Simple API for registering the Ajax Request Handler and the Ajax Response
      Handler

Overview of AjaxEngine

Using the AjaxEngine to create dynamic content is very straightforward. There are
three steps.

   1. Register the Ajax request handler. This tells the AjaxEngine that a specific
      web service or server call is mapped to a request handler name.
   2. Register the Ajax response handler. This is either specifies an HTML element
      as the target of the data being returned (in which case the contents of the
      response is HTML code) or it specifies a specific JavaScript object that will
      manage the response
   3. Invoke the Ajax request when the appropriate event occurs in the interface.


                                                                                    2
Rico AjaxEngine Tutorial

Before starting, make sure that you have included both prototype.js and rico.js in
your HTML page. You should include these two library files in your
<head></head> section like this:

 <script src="scripts/prototype.js"></script>
 <script src="scripts/rico.js"></script>


Rolodex Demo
Lets use the Rolodex demo from the openrico web site
(http://openrico.org/demos.page?demo=ricoAjaxInnerHTML.html).

Recall that by selecting persons from the list on the left, a rolodex card is displayed
on the right hand side.




For this demo we built a server-side process to handle requests for information
about a person. When the person is selected in the list we use Rico’s AjaxEngine to
call this request handler and then we process the response containing personal
information and display it as a rolodex card.

Step 1: Register a Request Handler
The first thing we must do is register this Request Handler with the Ajax engine. We
do this by associating the URL for a request handler with a given name. This name
will serve as the identifier for the Ajax request handler.

 ajaxEngine.registerRequest( ‘getPersonInfo’, ‘getPersonInfo.do’);


Notice the Ajax Engine is refereced with the identifier ajaxEngine. The included
rico.js file creates an instance of the Ajax Engine with this name making it available
to your page scripts to reference.


                                                                                      3
Rico AjaxEngine Tutorial

A request handler can be written in a number of different server languages or
mechanisms. Some of these include web services using SOAP or HTTP Rest
interfaces or with Java Server Pages (JSP), Jakarta Struts Actions, PHP code, ASP
code, Ruby code – and the list goes on.

In our current set of examples we use JSP/Jakarta        Jakarta Struts is an open
Struts to handle requests and generate the Ajax          source framework that
response. This means that we have written some           provides mechanisms for
Java code that handles the Ajax request for data. For    handling requests, responses,
example, in the Inner Html/Rolodex demo we have          page forwarding and other
register a request handler named getPersonInfo and       mechanisms that are required
                                                         by web applications.
map it to the URL getPersonInfo.do. an URL named
‘getPersonInfo.do’. This is a struts action that will    The .do is simple a convention
return the HTML for the rolodex when passed the          that means this is an Action
last and first name of the person.                       (an event handler.)

Try the Request Handler

Try this in your browser:
http://openrico.org/rico/getPersonInfo.do?firstName=Pat&lastName=Barnes

This is what you should see as the response:

 <ajax-response>
       <response type="element" id="personInfo">
             <div class="person"><span class="personName">Mr. Pat
             Barnes</span><span class="personAddress">1743 1st Avenue
             Boston, Boston 71204-2345</span><span
             class="personOccupation">Executive Vice
             President</span><span class="personPhoneNumber">Phone #:
             (972) 555-0293</span><span class="personMobile">Mobile #:
             (972) 555-0295</span><span class="personNotes">Notes:
             Spouse playes tennis at the country club with
             John.</span></div>
       </response>
 </ajax-response>



This is a typical Rico ajax-response. It contains a block of well-formed XML code.

Understanding the ajax-response in Rico

Notice several important items about the Ajax response

First the response is wrapped in the tags <ajax-response></ajax-response>. Every
Rico Ajax response must have this element as the root of the XML returned.


                                                                                          4
Rico AjaxEngine Tutorial

Second notice the response contained within the ajax-response. The response tags
(<response></response>.) wrap the response content An ajax-response in Rico is
not limited to a single response. It can contain multiple responses. Each response is
marked by the <response></response> set of tags.

  Every Rico Ajax             Third, notice the value of the type attribute. It is set to
  response must have          element. Also notice the value of the id attribute is set
  the <ajax-response>         to personInfo. Together this says to take the contents of
  element as its root         the response and copy it directly to the inner HTML of
  and at contain at           the element with id=personInfo – in this case a DIV on
  least one <response>        our page with the id set to personInfo. Later, we will
                              discuss the other type, object.
  element.
                           And last, notice that contained in the XML is a set of
well-formed XHTML code. The code in this example is the necessary HTML to
create a rolodex card (and coupled with the correct CSS style class) looks like this:




Step 2: Register a Response Handler
So we have a response. And we would like it to create a rolodex card as in our
example. How do we get the Ajax response HTML inserted into the contents of a
specific DIV on our HTML page?

The key is in the response.

Recall that our response specified the
   • type=”element”
   • id=”personInfo”

The element type of response indicates that we will be updating an Html element
directly whose id matches the response id. In this case if we specify a DIV (or


                                                                                            5
Rico AjaxEngine Tutorial

whatever HTML element that can contain innerHTML) with this id, then it will be
automatically updated with the content of the response.

Here is what our HTML roughly looks like. The DIV with id=personInfo will have
its content replaced with the HTML for the rolodex card.

 <div id="rolodexTabContent" class="accordionTabContentBox">
     <table cellspacing="5" cellpadding="5"><tr>
          <td valign="top">
              <select id="listBox" onchange="getPersonInfo(this)">
                   [snip]
              </select>
          </td>
          <td>
              <div style="display:inline" id="personInfo">
                   Select a name to the left to see the AJAX rolodex entry
                   for the selected person.
              </div>
          </td>
     </tr></table>
 </div>




The div that is in bold is the response handler. Two things are required for Rico to
recognize this element as the response handler:

   1. Give the element an id that matches the id of the response in the ajax-
      response
   2. Register the element id with Rico
      ajaxEngine.registerAjaxElement(‘personInfo’);

When the response returns the AjaxEngine will copy the response HTML into the
innerHTML of the DIV (personInfo). The result in this case would be equivalent to
the following HTML code:

 <div style="display:inline" id="personInfo">
    <div class="person"><span class="personName">Mr. Pat
    Barnes</span><span class="personAddress">1743 1st Avenue Boston,
    Boston 71204-2345</span><span class="personOccupation">Executive
    Vice President</span><span class="personPhoneNumber">Phone #:
    (972) 555-0293</span><span class="personMobile">Mobile #: (972)
    555-0295</span><span class="personNotes">Notes: Spouse playes
    tennis at the country club with John.</span></div>
 </div>


Step 3: Initiating a Request


                                                                                       6
Rico AjaxEngine Tutorial

This leads us to the third and final step, making the Ajax request. At this stage we
have both the request handler and the response handler registered.

What we need now is something to trigger the request. In the HTML code above,
notice we provided an event handler on the select. We registered a JavaScript
method to be fired on the onchange event in the <select> list. Every time a person
is selected in the list an Ajax request is initiated and the response gets populated in
the DIV on the right.

Here is how we set up our event on the HTML Select element.

  <select id="listBox" onchange="getPersonInfo(this)">


The getPerson function makes the Ajax request. Here is the method:

 function getPersonInfo(selectBox) {
       var nameToLookup = selectBox.value.split(",");
       var firstName = nameToLookup[1].substring(1);
       var lastName = nameToLookup[0];

         ajaxEngine.sendRequest( 'getPersonInfo',
                                 "firstName=" + firstName,
                                 "lastName=" + lastName );
 }


This function’s main responsibility is to call the sendRequest method on the Ajax
Engine passing the request parameters expected by our request handler (remember
our Struts Action, getPersonInfo.do?) Notice that it uses the name for the request
handler not the actual URL.

That’s it!! Let’s review how to get Ajax running in your page.

     1. Register your Ajax request handler
     2. Register your Ajax response handler
     3. Invoke sendRequest in the appropriate event.

Let’s look at the second type of response type—object. The Form Letter Updater
demo (http://openrico.org/demos.page?demo=ricoAjaxComplex.html.)

In this demo, selecting a person on the left causes the personal information to be
substituted into the form letter (a mail merge.)




                                                                                       7
Rico AjaxEngine Tutorial




Variant: The Object Response Type
Recall that when a response is provided in the ajax-response XML, its type was set
to element. It meant that the contents were to be targeted into an HTML element
with an id equal to the response id.

There is another response type named object. Instead of automatically inserting
HTML inside an HTML element, it calls a JavaScript object registered under the
name matching the id given here. The Ajax engine will call the object’s method
named ajaxUpdate. This method must be present to handle requests.

First, try this URL
http://openrico.org/rico/getPersonInfoXML.do?firstName=Pat&lastName=Barnes

You should see something like this:

 <ajax-response>
 <response type="object" id="formLetterUpdater">
      <person fullName="Pat Barnes" title="Mr." firstName="Pat"
      lastName="Barnes" streetAddress="1743 1st Avenue" city="Boston"
      state="Boston" zipcode="71204-2345" occupation="Executive Vice
      President" phoneNumber="(972) 555-0293" mobileNumber="(972)
      555-0295" personNotes="Spouse playes tennis at the country club
      with John." />
 </response>
 </ajax-response>


Notice in our case the content of the response is XML code describing a single
person. Obviously the content is completely application specific. We are retrieving
fields of information about a person as XML attributes.



                                                                                     8
Rico AjaxEngine Tutorial

In order to handle this XML format, we must write a JavaScript object that has an
ajaxUpdate method. When the response is returned, the AjaxEngine will note that it
is of object type and locate the JavaScript object that has been registered under a
name matching the response id.

It is the duty of the ajaxUpdate method to parse this XML response and do with it as
necessary in the application. Here is the ajaxUpdate method signature:

 ajaxUpdate(ajaxResponse)



When a request is made, the XML is processed by the JavaScript object and the
appropriate person data is inserted into the form letter.

Here is what the FormLetterUpdater object does with the ajax response:

     ajaxUpdate: function(ajaxResponse) {
        this.setPerson(ajaxResponse.childNodes[0]);
     },

     setPerson: function(aPerson) {
        this.lastPersonSelected = aPerson;
        for ( var i = 0 ;i < FormLetterUpdater.attributes.length ;i++ )
        {
           var attr = FormLetterUpdater.attributes[i];
           this.substitute( "span", attr, this.emphasizedHTML(
                           aPerson.getAttribute(attr) ) );
        }
     },

     substitute: function( tagName, tagClass, value ) {
         var elements = document.getElementsByTagAndClassName(
                           tagName, tagClass);
         for ( var i = 0 ; i < elements.length ; i++ )
            elements[i].innerHTML = value;
      },




Notice the ajaxUpdate expects one child as its node—a person. This is passed to
the setPerson method. The FormLetterUpdater:setPerson method iterates over the
attributes found on the person object and locates spans with the same id and
substitutes the attribute values into the innerHTML of each span.

Since you can define your response any way you want (as long as the response is
valid XML markup) you can process the response data anyway you see fit.




                                                                                  9
Rico AjaxEngine Tutorial

Here is a snippet of the HTML code that makes up the form letter. The HTML
contains a number of spans that have the id matching the response attribute id. Our
ajaxUpdate method uses this to perform a simple substitution:

 <p>
        Please take a moment to verify the billing/shipping
        information that you gave us.
        If any of the information is incorrect, please contact one of
        our customer service
        representatives at (800)-555-RNCO.
 </p>
 <div style="width:250px;margin-left:50px;margin-bottom:15px;">
 <span class="fullName">[fullName]</span><br/>
 <span class="streetAddress">[streetAddress]</span><br/>
 <span style="text-align:right" class="city">[addresscity]</span>,
 <span class="state">[addressState]</span>
 <span class="zipcode">[addressZipcode]</span><br/><br/>


Registering the Ajax Object
Just like we registered an element (AjaxEngine.registerElement) if you are going to
have a request handler that is a JavaScript object you will need to register the
object with the Ajax Engine.

 ajaxEngine.registerAjaxObject(‘formLetterUpdater’,
                               new FormLetterUpdater());



Differences
So what is the difference between the two types of responses?

The response type element is for simple updating of an HTML element’s content
with some HTML.

The response type object allows for custom or more advanced manipulation of the
response data to update the page content.

Multiple Responses
Don’t forget that you can also embed multiple responses in the same ajax-response.
You can also mix element and object responses in the same ajax-response.

Summary
In summary, the Rico AjaxEngine simplifies updating page content with Ajax. It
provides a very straightforward way to change the HTML content of any HTML
element. But it also provides an open ended way to respond to more complex data
sets returned via a JavaScript object.



                                                                                  10

Weitere ähnliche Inhalte

Was ist angesagt? (20)

jQuery Ajax
jQuery AjaxjQuery Ajax
jQuery Ajax
 
RESTful Web Services with JAX-RS
RESTful Web Services with JAX-RSRESTful Web Services with JAX-RS
RESTful Web Services with JAX-RS
 
API
APIAPI
API
 
SynapseIndia dotnet development ajax client library
SynapseIndia dotnet development ajax client librarySynapseIndia dotnet development ajax client library
SynapseIndia dotnet development ajax client library
 
Jsp & Ajax
Jsp & AjaxJsp & Ajax
Jsp & Ajax
 
Intro to flask2
Intro to flask2Intro to flask2
Intro to flask2
 
Rest in Rails
Rest in RailsRest in Rails
Rest in Rails
 
Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)
 
Rest and Rails
Rest and RailsRest and Rails
Rest and Rails
 
Asp.net server control
Asp.net  server controlAsp.net  server control
Asp.net server control
 
Data Access Options in SharePoint 2010
Data Access Options in SharePoint 2010Data Access Options in SharePoint 2010
Data Access Options in SharePoint 2010
 
AJAX
AJAXAJAX
AJAX
 
Intoduction to php web services and json
Intoduction to php  web services and jsonIntoduction to php  web services and json
Intoduction to php web services and json
 
Easy rest service using PHP reflection api
Easy rest service using PHP reflection apiEasy rest service using PHP reflection api
Easy rest service using PHP reflection api
 
WebLogic Developer Webcast 1: JPA 2.0
WebLogic Developer Webcast 1: JPA 2.0WebLogic Developer Webcast 1: JPA 2.0
WebLogic Developer Webcast 1: JPA 2.0
 
Ajax
AjaxAjax
Ajax
 
Ajax.ppt
Ajax.pptAjax.ppt
Ajax.ppt
 
RESTful Web Services
RESTful Web ServicesRESTful Web Services
RESTful Web Services
 
Learn Ajax here
Learn Ajax hereLearn Ajax here
Learn Ajax here
 
Ajax
AjaxAjax
Ajax
 

Andere mochten auch (20)

lecture5
lecture5lecture5
lecture5
 
cs3157-summer06-lab1
cs3157-summer06-lab1cs3157-summer06-lab1
cs3157-summer06-lab1
 
Data As Air
Data As AirData As Air
Data As Air
 
Tutorial5
Tutorial5Tutorial5
Tutorial5
 
Devfest09 Cschalk Gwt
Devfest09 Cschalk GwtDevfest09 Cschalk Gwt
Devfest09 Cschalk Gwt
 
oops09
oops09oops09
oops09
 
I S T H I S T H I S S T R E S S M A N A G E M E N T D R S H R I N I W A...
I S  T H I S  T H I S  S T R E S S  M A N A G E M E N T  D R  S H R I N I W A...I S  T H I S  T H I S  S T R E S S  M A N A G E M E N T  D R  S H R I N I W A...
I S T H I S T H I S S T R E S S M A N A G E M E N T D R S H R I N I W A...
 
Alaskan Railroad
Alaskan RailroadAlaskan Railroad
Alaskan Railroad
 
Perl-crash-course
Perl-crash-coursePerl-crash-course
Perl-crash-course
 
rbguiqt
rbguiqtrbguiqt
rbguiqt
 
cisco_cv
cisco_cvcisco_cv
cisco_cv
 
fms9_cwp_php_en
fms9_cwp_php_enfms9_cwp_php_en
fms9_cwp_php_en
 
phptut4
phptut4phptut4
phptut4
 
drmaatutggf12
drmaatutggf12drmaatutggf12
drmaatutggf12
 
AcroButtonsTutorial
AcroButtonsTutorialAcroButtonsTutorial
AcroButtonsTutorial
 
eureka09
eureka09eureka09
eureka09
 
由一个简单的程序谈起――之三(精华)
由一个简单的程序谈起――之三(精华)由一个简单的程序谈起――之三(精华)
由一个简单的程序谈起――之三(精华)
 
Letter of Rec (from Reh-Lin Chen)
Letter of Rec (from Reh-Lin Chen)Letter of Rec (from Reh-Lin Chen)
Letter of Rec (from Reh-Lin Chen)
 
moscowpm-perlevents
moscowpm-perleventsmoscowpm-perlevents
moscowpm-perlevents
 
SWtrngGB
SWtrngGBSWtrngGB
SWtrngGB
 

Ähnlich wie RicoAjaxEngine (20)

Ajax
AjaxAjax
Ajax
 
AJAX
AJAXAJAX
AJAX
 
AJAX
AJAXAJAX
AJAX
 
Ajax
AjaxAjax
Ajax
 
Using Ajax In Domino Web Applications
Using Ajax In Domino Web ApplicationsUsing Ajax In Domino Web Applications
Using Ajax In Domino Web Applications
 
Ajax
AjaxAjax
Ajax
 
Unit-5.pptx
Unit-5.pptxUnit-5.pptx
Unit-5.pptx
 
Ajax
AjaxAjax
Ajax
 
ajax_pdf
ajax_pdfajax_pdf
ajax_pdf
 
ajax_pdf
ajax_pdfajax_pdf
ajax_pdf
 
Ajax tutorial by bally chohan
Ajax tutorial by bally chohanAjax tutorial by bally chohan
Ajax tutorial by bally chohan
 
M Ramya
M RamyaM Ramya
M Ramya
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
Introduction to Web Architecture
Introduction to Web ArchitectureIntroduction to Web Architecture
Introduction to Web Architecture
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajax
 
Ajax
AjaxAjax
Ajax
 

Mehr von tutorialsruby

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>tutorialsruby
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008tutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheetstutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheetstutorialsruby
 

Mehr von tutorialsruby (20)

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
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" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
CSS
CSSCSS
CSS
 
CSS
CSSCSS
CSS
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 

Kürzlich hochgeladen

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 

Kürzlich hochgeladen (20)

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 

RicoAjaxEngine

  • 1. Rico AjaxEngine Tutorial The Rico JavaScript library provides a single JavaScript object, AjaxEngine, for adding Ajax to any HTML page. What is Ajax? Widkipedia has the following definition for Ajax: Traditional web applications allow users to fill out forms, and when these forms are submitted, a request is sent to a web server. The web server acts upon whatever was sent by the form, and then responds back by sending a new web page. A lot of bandwidth is wasted since much of the HTML from the first page is present in the second page. Because a request to the web server has to be transmitted on every interaction with the application, the application's response time is dependant on the response time of the web server. This leads to user interfaces that are much slower than their native counterparts. AJAX applications, on the other hand, can send requests to the web server to retrieve only the data that is needed, usually using SOAP or some other XML-based web services dialect, and using JavaScript in the client to process the web server response. The result is more responsive applications, since the amount of data interchanged between the web browser and web server is vastly reduced. Web server processing time is also saved, since a lot of this is done on the computer from which the request came. Comparing Ajax to Normal HTTP Mechanism As stated above, the traditional way users interact with a page is to click a link (usually translates to an HTTP GET request) or click a submit button on a form (usually translates to an HTTP POST request request). In the first case, a new page Web Page Web is requested and the browser Web Page Server refreshes with new content. In the response second case, either a new page or the same page with modified values is returned. In Ajax the request is made using the JavaScript function XmlHttpRequest. The request asks for a block of XML data (rather than a whole page to refresh) that the JavaScript code can handle in whatever way it sees fit. For example, here are some ways the XML data could be interpreted: • XML data that the JavaScript code parses to extract data. This data in turn is used to fill in field values or tables in a display. 1
  • 2. Rico AjaxEngine Tutorial • XML data that the JavaScript runs an XSLT process on to convert into HTML code to be inserted on the page somewhere • XML data that holds JavaScript that the JavaScript code evaluates to issue commands • XML data that contains HTML code that can be placed inside another HTML element on the page This list is not exhaustive. The point is – Ajax allows you to make a server side call outside of the normal page refresh cycle. The data that is returned can be defined in any manner that XML allows and the way it is interpreted is open to the application’s determined usage of this data. Rico AjaxEngine Rico provides a JavaScript object named AjaxEngine that simplifies using Ajax to update the contents within a page. The engine provides the following features: • A standard XML definition for the basic Ajax response • A way to specify that a response is targeted for a specific HTML element • Automatic update of the targeted HTML element’s innerHTML with the contents of the response • A way to specify that a response is targeted for a specific JavaScript Ajax response handler • Standard mechanism for an Ajax response handler to receive response messages • Support for multiple Ajax responses as the result of one Ajax request (multiple updates to elements and/or JavaScript objects). • Simple API for registering the Ajax Request Handler and the Ajax Response Handler Overview of AjaxEngine Using the AjaxEngine to create dynamic content is very straightforward. There are three steps. 1. Register the Ajax request handler. This tells the AjaxEngine that a specific web service or server call is mapped to a request handler name. 2. Register the Ajax response handler. This is either specifies an HTML element as the target of the data being returned (in which case the contents of the response is HTML code) or it specifies a specific JavaScript object that will manage the response 3. Invoke the Ajax request when the appropriate event occurs in the interface. 2
  • 3. Rico AjaxEngine Tutorial Before starting, make sure that you have included both prototype.js and rico.js in your HTML page. You should include these two library files in your <head></head> section like this: <script src="scripts/prototype.js"></script> <script src="scripts/rico.js"></script> Rolodex Demo Lets use the Rolodex demo from the openrico web site (http://openrico.org/demos.page?demo=ricoAjaxInnerHTML.html). Recall that by selecting persons from the list on the left, a rolodex card is displayed on the right hand side. For this demo we built a server-side process to handle requests for information about a person. When the person is selected in the list we use Rico’s AjaxEngine to call this request handler and then we process the response containing personal information and display it as a rolodex card. Step 1: Register a Request Handler The first thing we must do is register this Request Handler with the Ajax engine. We do this by associating the URL for a request handler with a given name. This name will serve as the identifier for the Ajax request handler. ajaxEngine.registerRequest( ‘getPersonInfo’, ‘getPersonInfo.do’); Notice the Ajax Engine is refereced with the identifier ajaxEngine. The included rico.js file creates an instance of the Ajax Engine with this name making it available to your page scripts to reference. 3
  • 4. Rico AjaxEngine Tutorial A request handler can be written in a number of different server languages or mechanisms. Some of these include web services using SOAP or HTTP Rest interfaces or with Java Server Pages (JSP), Jakarta Struts Actions, PHP code, ASP code, Ruby code – and the list goes on. In our current set of examples we use JSP/Jakarta Jakarta Struts is an open Struts to handle requests and generate the Ajax source framework that response. This means that we have written some provides mechanisms for Java code that handles the Ajax request for data. For handling requests, responses, example, in the Inner Html/Rolodex demo we have page forwarding and other register a request handler named getPersonInfo and mechanisms that are required by web applications. map it to the URL getPersonInfo.do. an URL named ‘getPersonInfo.do’. This is a struts action that will The .do is simple a convention return the HTML for the rolodex when passed the that means this is an Action last and first name of the person. (an event handler.) Try the Request Handler Try this in your browser: http://openrico.org/rico/getPersonInfo.do?firstName=Pat&lastName=Barnes This is what you should see as the response: <ajax-response> <response type="element" id="personInfo"> <div class="person"><span class="personName">Mr. Pat Barnes</span><span class="personAddress">1743 1st Avenue Boston, Boston 71204-2345</span><span class="personOccupation">Executive Vice President</span><span class="personPhoneNumber">Phone #: (972) 555-0293</span><span class="personMobile">Mobile #: (972) 555-0295</span><span class="personNotes">Notes: Spouse playes tennis at the country club with John.</span></div> </response> </ajax-response> This is a typical Rico ajax-response. It contains a block of well-formed XML code. Understanding the ajax-response in Rico Notice several important items about the Ajax response First the response is wrapped in the tags <ajax-response></ajax-response>. Every Rico Ajax response must have this element as the root of the XML returned. 4
  • 5. Rico AjaxEngine Tutorial Second notice the response contained within the ajax-response. The response tags (<response></response>.) wrap the response content An ajax-response in Rico is not limited to a single response. It can contain multiple responses. Each response is marked by the <response></response> set of tags. Every Rico Ajax Third, notice the value of the type attribute. It is set to response must have element. Also notice the value of the id attribute is set the <ajax-response> to personInfo. Together this says to take the contents of element as its root the response and copy it directly to the inner HTML of and at contain at the element with id=personInfo – in this case a DIV on least one <response> our page with the id set to personInfo. Later, we will discuss the other type, object. element. And last, notice that contained in the XML is a set of well-formed XHTML code. The code in this example is the necessary HTML to create a rolodex card (and coupled with the correct CSS style class) looks like this: Step 2: Register a Response Handler So we have a response. And we would like it to create a rolodex card as in our example. How do we get the Ajax response HTML inserted into the contents of a specific DIV on our HTML page? The key is in the response. Recall that our response specified the • type=”element” • id=”personInfo” The element type of response indicates that we will be updating an Html element directly whose id matches the response id. In this case if we specify a DIV (or 5
  • 6. Rico AjaxEngine Tutorial whatever HTML element that can contain innerHTML) with this id, then it will be automatically updated with the content of the response. Here is what our HTML roughly looks like. The DIV with id=personInfo will have its content replaced with the HTML for the rolodex card. <div id="rolodexTabContent" class="accordionTabContentBox"> <table cellspacing="5" cellpadding="5"><tr> <td valign="top"> <select id="listBox" onchange="getPersonInfo(this)"> [snip] </select> </td> <td> <div style="display:inline" id="personInfo"> Select a name to the left to see the AJAX rolodex entry for the selected person. </div> </td> </tr></table> </div> The div that is in bold is the response handler. Two things are required for Rico to recognize this element as the response handler: 1. Give the element an id that matches the id of the response in the ajax- response 2. Register the element id with Rico ajaxEngine.registerAjaxElement(‘personInfo’); When the response returns the AjaxEngine will copy the response HTML into the innerHTML of the DIV (personInfo). The result in this case would be equivalent to the following HTML code: <div style="display:inline" id="personInfo"> <div class="person"><span class="personName">Mr. Pat Barnes</span><span class="personAddress">1743 1st Avenue Boston, Boston 71204-2345</span><span class="personOccupation">Executive Vice President</span><span class="personPhoneNumber">Phone #: (972) 555-0293</span><span class="personMobile">Mobile #: (972) 555-0295</span><span class="personNotes">Notes: Spouse playes tennis at the country club with John.</span></div> </div> Step 3: Initiating a Request 6
  • 7. Rico AjaxEngine Tutorial This leads us to the third and final step, making the Ajax request. At this stage we have both the request handler and the response handler registered. What we need now is something to trigger the request. In the HTML code above, notice we provided an event handler on the select. We registered a JavaScript method to be fired on the onchange event in the <select> list. Every time a person is selected in the list an Ajax request is initiated and the response gets populated in the DIV on the right. Here is how we set up our event on the HTML Select element. <select id="listBox" onchange="getPersonInfo(this)"> The getPerson function makes the Ajax request. Here is the method: function getPersonInfo(selectBox) { var nameToLookup = selectBox.value.split(","); var firstName = nameToLookup[1].substring(1); var lastName = nameToLookup[0]; ajaxEngine.sendRequest( 'getPersonInfo', "firstName=" + firstName, "lastName=" + lastName ); } This function’s main responsibility is to call the sendRequest method on the Ajax Engine passing the request parameters expected by our request handler (remember our Struts Action, getPersonInfo.do?) Notice that it uses the name for the request handler not the actual URL. That’s it!! Let’s review how to get Ajax running in your page. 1. Register your Ajax request handler 2. Register your Ajax response handler 3. Invoke sendRequest in the appropriate event. Let’s look at the second type of response type—object. The Form Letter Updater demo (http://openrico.org/demos.page?demo=ricoAjaxComplex.html.) In this demo, selecting a person on the left causes the personal information to be substituted into the form letter (a mail merge.) 7
  • 8. Rico AjaxEngine Tutorial Variant: The Object Response Type Recall that when a response is provided in the ajax-response XML, its type was set to element. It meant that the contents were to be targeted into an HTML element with an id equal to the response id. There is another response type named object. Instead of automatically inserting HTML inside an HTML element, it calls a JavaScript object registered under the name matching the id given here. The Ajax engine will call the object’s method named ajaxUpdate. This method must be present to handle requests. First, try this URL http://openrico.org/rico/getPersonInfoXML.do?firstName=Pat&lastName=Barnes You should see something like this: <ajax-response> <response type="object" id="formLetterUpdater"> <person fullName="Pat Barnes" title="Mr." firstName="Pat" lastName="Barnes" streetAddress="1743 1st Avenue" city="Boston" state="Boston" zipcode="71204-2345" occupation="Executive Vice President" phoneNumber="(972) 555-0293" mobileNumber="(972) 555-0295" personNotes="Spouse playes tennis at the country club with John." /> </response> </ajax-response> Notice in our case the content of the response is XML code describing a single person. Obviously the content is completely application specific. We are retrieving fields of information about a person as XML attributes. 8
  • 9. Rico AjaxEngine Tutorial In order to handle this XML format, we must write a JavaScript object that has an ajaxUpdate method. When the response is returned, the AjaxEngine will note that it is of object type and locate the JavaScript object that has been registered under a name matching the response id. It is the duty of the ajaxUpdate method to parse this XML response and do with it as necessary in the application. Here is the ajaxUpdate method signature: ajaxUpdate(ajaxResponse) When a request is made, the XML is processed by the JavaScript object and the appropriate person data is inserted into the form letter. Here is what the FormLetterUpdater object does with the ajax response: ajaxUpdate: function(ajaxResponse) { this.setPerson(ajaxResponse.childNodes[0]); }, setPerson: function(aPerson) { this.lastPersonSelected = aPerson; for ( var i = 0 ;i < FormLetterUpdater.attributes.length ;i++ ) { var attr = FormLetterUpdater.attributes[i]; this.substitute( "span", attr, this.emphasizedHTML( aPerson.getAttribute(attr) ) ); } }, substitute: function( tagName, tagClass, value ) { var elements = document.getElementsByTagAndClassName( tagName, tagClass); for ( var i = 0 ; i < elements.length ; i++ ) elements[i].innerHTML = value; }, Notice the ajaxUpdate expects one child as its node—a person. This is passed to the setPerson method. The FormLetterUpdater:setPerson method iterates over the attributes found on the person object and locates spans with the same id and substitutes the attribute values into the innerHTML of each span. Since you can define your response any way you want (as long as the response is valid XML markup) you can process the response data anyway you see fit. 9
  • 10. Rico AjaxEngine Tutorial Here is a snippet of the HTML code that makes up the form letter. The HTML contains a number of spans that have the id matching the response attribute id. Our ajaxUpdate method uses this to perform a simple substitution: <p> Please take a moment to verify the billing/shipping information that you gave us. If any of the information is incorrect, please contact one of our customer service representatives at (800)-555-RNCO. </p> <div style="width:250px;margin-left:50px;margin-bottom:15px;"> <span class="fullName">[fullName]</span><br/> <span class="streetAddress">[streetAddress]</span><br/> <span style="text-align:right" class="city">[addresscity]</span>, <span class="state">[addressState]</span> <span class="zipcode">[addressZipcode]</span><br/><br/> Registering the Ajax Object Just like we registered an element (AjaxEngine.registerElement) if you are going to have a request handler that is a JavaScript object you will need to register the object with the Ajax Engine. ajaxEngine.registerAjaxObject(‘formLetterUpdater’, new FormLetterUpdater()); Differences So what is the difference between the two types of responses? The response type element is for simple updating of an HTML element’s content with some HTML. The response type object allows for custom or more advanced manipulation of the response data to update the page content. Multiple Responses Don’t forget that you can also embed multiple responses in the same ajax-response. You can also mix element and object responses in the same ajax-response. Summary In summary, the Rico AjaxEngine simplifies updating page content with Ajax. It provides a very straightforward way to change the HTML content of any HTML element. But it also provides an open ended way to respond to more complex data sets returned via a JavaScript object. 10