fhg
Volume 8, Number 40 -- November 19, 2008

Getting Started With AJAX

Published: November 19, 2008

by Paul Tuohy

In this article, we will see how AJAX works by looking at a simple example of using AJAX to retrieve the description (from the server) for a code entered on a Web page.

Remember one of the main benefits of AJAX is that communication between the Web page and the server is asynchronous. This means that the Web page may be updated with information from the server without the user having to click any submit button.

An Example

Figure 1 shows the Web page initially displayed to the user, and it also shows the contents of the page after the user has entered a product code and the server retrieved a description.


Figure 1: Retrieving a Product Description with AJAX

The example has two HTML pages: ajax1.html is the requesting HTML document; and ajax2.html is the response document that is returned to the ajax1.html requesting document. It also has one RPG CGI program: AJAX2 processes the request from the browser and returns the product description. The RPG CGI program makes use of CGIDEV2.

AJAX and RPG Programming: The XMLHttpRequest Object

AJAX is implemented through JavaScript's XMLHttpRequest object, which provides a set of methods (functions) and variables that allow a Web page to send data to and receive data from a server. To enable an AJAX conversation between the browser and the server, your Web page must first instantiate an XMLHttpRequest object.

You make use of the XMLHttpRequest object's open() and send() methods to "call' an RPG program; the request is in the same format of any CGI request on a hyperlink or in a form.

The XMLHttpRequest object's onreadystatechange, readyState, status, and responseText variables are used to determine the data received from the server, and you code a function to process it.

This complete process of issuing the call and receiving and processing the returned data is asynchronous.

The RPG program is like any other CGI program. The only difference is in the format and content of the data returned. But you will find yourself writing programs in a different way to cater for multiple AJAX calls. (E.g., the same program may be called multiple times performing a different field validation on each call.)

The HTML Documents

The following code shows the HTML for ajax1.html, the requesting document:

<script TYPE="text/JavaScript">            
   <!-- Definition of JavaScript functions 
         createXMLHttp() & callServer() here -->
 </script>

 <html>

    <head>
       <title>Simple example of AJAX at Work</title>
    </head>

    <body> 
      <a href="ajax0.html">Menu</a>
      <center><h1>Ajax at Work!</h1>
       <h2>Simple example of AJAX at Work</h2></center>

      <p>Enter a valid product code (0000001) and the 
           description is displayed </p>

         <table border=0>
             <tr><td>Product Code: 
                     <input type="text" id = prodcd 
                      name=prodcd size=7 maxlength=7              
                      onChange="callServer()">
                  </td>   
                 <td><div id="prodds" ></div></td>           
             </tr>
         </table>
    </body>
 </html>

The main points to note are:

  1. The JavaScript functions--createXMLHttp() and callServer()--have been removed for clarity (more in a moment).
  2. The definition of the prodcd entry in the form specifies that the callServer() function should run when the contents of the field change. This means that the callServer() function is called when a user enters a value and moves the cursor out of the field (using the keyboard or the mouse).
  3. The contents of the div delimiters (id="prods") are updated with the value returned from the AJAX call to the server.

The next piece of code shows the HTML for the content returned by the RPG program on the AJAX call. In the example below, the program returns a table with one row and one cell containing the product description. This is a standard CGIDEV2 document with a section named "top" and a single variable named "prods". Even though it is not a new page that displays, the Content-type is still required at the start of the page.

/$top
Content-type: text/html

<table border=0>
 <tr><td>/%prodds%/</td></tr>
</table>

This table will be placed in the <DIV> identified by the "prods" id in the first piece of code.

The RPG Program

The next code shows a standard CGIDEV2 program that:

  • Uses the getHTMLIFS() subprocedure to load the document described in the HTML for the content returned by the RPG program
  • Uses the zhbGetVar() subprocedure to retrieve the value of the requested product code
  • Uses the updHTMLVar() subprocedure to place the product description in the returned document
  • Uses the wrtSection() subprocedure to write the document back to the server, which, in turn, returns it to the requesting page

This example shows ajax2.html, the RPG program that returns the description:

H Option(*SrcStmt:*NoDebugIO)
H DftActGrp(*No) ActGrp('AGCGI') BndDir('ALLBNDDIR')

FProduct1  IF   E           K Disk    ExtFile('AJAXLIB/PRODUCT1')

 /Copy PROTOTYPEB
 /Copy USEC

D SavedQryStr     S           2000A   Varying

 /Free
    gethtmlIFS('/ajaxdocs/ajax2.html');

    If ZhbGetInput(SavedQryStr: QUSEC) > 0;
       ProdCd = ZhbGetVar('prodcd');
       Chain ProdCd Product1;
       If Not %Found(Product1);
          ProdDs = '*** Product Not Found ***';
       EndIf;
       updHTMLvar('prodds':prodds);
       wrtsection('datarow');
    EndIf;

    wrtSection('top *fini');
    Return;
 /End-Free             

The AJAX Bit!

Now we come to the crunch, the two JavaScript functions that will do all of the work: createXMLHttp() and callServer(). These are the two JavaScript functions coded between the script tags at the start of the ajax1.html.

For completions sake, the next piece of code shows an example of a function to instantiate an XMLHttpRequest object. Usually you won't have to code this, you will simply use the one included in whichever AJAX toolbox or framework you happen to download.

   function createXMLHttp() {
      if (typeof XMLHttpRequest != "undefined") {
          return new XMLHttpRequest(); 
      } else if (window.ActiveXObject) {
            var aVersions = ["MSXML2.XmlHttp.5.0",
                       "MSXML2.XmlHttp.4.0","MSXML2.XmlHttp.3.0",
                       "MSXML2.XmlHttp", "Microsoft.XmlHttp"];
          for (var i = 0; i < aVersions.length; i++) {
            try {
              var oXmlHttp = new ActiveXObject(aVersions[i]);
              return oXmlHttp;
            } catch (oError) {
            }
          alert("Could not connect");
          }
      }
      throw new Error ("Could not create an XMLHttp object");
   }

This is a great example of the "which browser" problem faced by Web developers. The exact object used depends on which browser is being used. The XMLHttpRequest object is supported by all current browsers, but in releases of IE prior to version 7, support is through a Microsoft proprietary interface (ActiveX objects); luckily that interface is 100 percent compatible with XMLHttpRequest.

At last, the final piece of code shows the callServer() function that does all the AJAX work:

      function callServer() {
(1)      var prodcd = document.getElementById("prodcd").value;
(2)      var url = "/ajax/AJAX2?prodcd=" + escape(prodcd);
(3)      var xmlHttp = createXMLHttp();
  
(4)      xmlHttp.open("GET", url, true);

(5)      xmlHttp.onreadystatechange = function() {
(6)         if (xmlHttp.readyState == 4) {
                if (xmlHttp.status == 200) {
                   document.getElementById("prodds").innerHTML 
                           = xmlHttp.responseText;
                } else {
                   alert("An error occurred trying to contact the server.");
                }
             }
         }
(7)      xmlHttp.send(null);
      }

The main points to note (refer to the numbers in the above code):

  1. The variable prodcd is set to the value entered for the field in the form
  2. The variable url identifies the CGI program to call. The URL is constructed the same as any CGI call--this example calls the program AJAX2 and passing a parameter for the product code and the value entered. Values for parameters must be encoded, which does not happen automatically as it does on a normal CGI call from a hyperlink or a form, so you must use the escape() or the encodeURIComponent() function to encode the values (both are standard with escape() being the older of the two)
  3. The xmlHttp variable is the XMLHttpRequest object that is instantiated using the createXMLHttp() function. The methods and variables of this object will perform the AJAX communication
  4. The open() method takes three parameters--whether the request is sent using GET or POST, the URL, and an indicator that is true for asynchronous and false for synchronous. The open() method does not actually send the request; it simply identifies the connection (much like opening a file in a program)
  5. The onreadystatechange attribute identifies the function to run when the server sends a reply
  6. When the readyState is completed (value of 4) and the status is success (value of 200), then the code sets the contents of the div section (identified by the id of prods) equal to the responseText value returned from the server. The responseText value is the complete document returned from the program call
  7. The send() method sends the request. There is no delay in the browser. The request runs in the background. The onreadystatechange function runs automatically when the server returns data

Obviously, the real work is done in the final step when the data returned from the server is processed (in this case, the data is simply some HTML text).

The readyState may have a value of 0=Un-initialized, 1=Loading, 2=Finished Loading, 3=Retrieving Data or 4=Completed.

The status may be one of the standard server status codes: 404=Not Found, 501=Not Authorized, etc.

That’s the Gist!

Hopefully this gives you some idea of how easy it is to use AJAX.

When it comes down to it using AJAX is really about mastering Javascript in order to "communicate" with the Web page. The server side of the process is very simple.


Paul Tuohy is CEO of ComCon, an iSeries consulting company, and is one of the co-founders of System i Developer, which hosts the RPG & DB2 Summit conferences. He is an award-winning speaker who also speaks regularly at COMMON conferences, and is the author of "Re-engineering RPG Legacy Applications," "The Programmers Guide to iSeries Navigator," and the self-study course called "iSeries Navigator for Programmers." Send your questions or comments for Paul to Ted Holt via the IT Jungle Contact page.


RELATED STORY

What is AJAX?



                     Post this story to del.icio.us
               Post this story to Digg
    Post this story to Slashdot


Sponsored By
PROFOUND LOGIC SOFTWARE

Need Results Fast?
Web-enable with Genie!

                                                          · Easy Installation
                                                          · Codeless Customizations
                                                          · Instant Results

With Genie on your side, you can be
modernized in less than a day. Simply
install, customize, and deploy.

See the magic of Genie today.

Download a FREE 30-day trial at
www.profoundlogic.com


Senior Technical Editor: Ted Holt
Technical Editor: Joe Hertvik
Contributing Technical Editors: Edwin Earley, Brian Kelly, Michael Sansoterra
Publisher and Advertising Director: Jenny Thomas
Advertising Sales Representative: Kim Reed
Contact the Editors: To contact anyone on the IT Jungle Team
Go to our contacts page and send us a message.

Sponsored Links

COMMON:  Join us at the 2009 annual meeting and expo, April 26-30, Reno, Nevada
Databorough:  Upgrade your iSeries tools with X-Analysis
Help/Systems:  SEQUEL meets your System i data access and analysis needs


 

IT Jungle Store Top Book Picks

Easy Steps to Internet Programming for AS/400, iSeries, and System i: List Price, $49.95
Getting Started with PHP for i5/OS: List Price, $59.95
The System i RPG & RPG IV Tutorial and Lab Exercises: List Price, $59.95
The System i Pocket RPG & RPG IV Guide: List Price, $69.95
The iSeries Pocket Database Guide: List Price, $59.00
The iSeries Pocket Developers' Guide: List Price, $59.00
The iSeries Pocket SQL Guide: List Price, $59.00
The iSeries Pocket Query Guide: List Price, $49.00
The iSeries Pocket WebFacing Primer: List Price, $39.00
Migrating to WebSphere Express for iSeries: List Price, $49.00
iSeries Express Web Implementer's Guide: List Price, $59.00
Getting Started with WebSphere Development Studio for iSeries: List Price, $79.95
Getting Started With WebSphere Development Studio Client for iSeries: List Price, $89.00
Getting Started with WebSphere Express for iSeries: List Price, $49.00
WebFacing Application Design and Development Guide: List Price, $55.00
Can the AS/400 Survive IBM?: List Price, $49.00
The All-Everything Machine: List Price, $29.95
Chip Wars: List Price, $29.95


 
The Four Hundred
Lotus Foundations and Smart Cube i: Brothers or Clones?

IBM Starts Cutting Deals on Power Systems i for Q4

Layoffs--Possibly Including Frank Soltis--at IBM Rochester

Mad Dog 21/21: Souls of Old Machines

Power Systems GM Discusses Upcoming i Announcements in Chat

The Linux Beacon
Why Blade Servers Still Don't Cut It, and How They Might

Intel Keeps Both Arms Swinging with Xeons, Jabs with Itanium

Microsoft Ponies Up Another $100 Million for Novell Linux

Mad Dog 21/21: Newtonian Economics

Two More Xeon-Based Galaxy Servers from Sun

Four Hundred Stuff
SkyView Goes GUI with i OS Security Tool

Gillani Hopes to Expand Presence on Power Systems

Agilysys Helps Casinos Cut the Fat with SWS 8.0

Seagull Swoops Back Into i OS

Bally Updates System i Gaming Systems

Big Iron
For Some Customers, the Mainframe Is Green

Top Mainframe Stories From Around the Web

Chats, Webinars, Seminars, Shows, and Other Happenings

System i PTF Guide
November 8, 2008: Volume 10, Number 45

November 1, 2008: Volume 10, Number 44

October 25, 2008: Volume 10, Number 43

October 18, 2008: Volume 10, Number 42

October 11, 2008: Volume 10, Number 41

October 4, 2008: Volume 10, Number 40

The Windows Observer
Citrix Addresses Performance with XenApp 5

Server Buyers Shop Like It's 1999 in the Second Quarter

Intel Keeps Both Arms Swinging with Xeons, Jabs with Itanium

Mad Dog 21/21: Newtonian Economics

Microsoft Does Something About Those SQL Injection Attacks

The Unix Guardian
What the Heck Is the Midrange, Anyway?

Overseas and Notebook Sales Offset Printer Declines for HP in Q3

Two More Xeon-Based Galaxy Servers from Sun

Mad Dog 21/21: Newtonian Economics

Intel's Nehalems to Star at IDF, AMD Pitches Shanghai

Four Hundred Monitor
Four Hundred Monitor's
Full iSeries Events Calendar

THIS ISSUE SPONSORED BY:

Profound Logic Software
Help/Systems
WorksRight Software


Printer Friendly Version


TABLE OF CONTENTS
Getting Started With AJAX

Enable Programmatic Access to Remote DB2 Data Using DRDA

Admin Alert: When Batch Meets Interactive

Four Hundred Guru

BACK ISSUES

From the IT Jungle Forums
Insert via Java

iSeries Access for Web

Mimix installation and configuration docs

EDI Inovis Programmer - Heavy Duty Problem Solver - Anytime

Data Queues vs. MQ Series: Performance

Removing blanks from a CL Variable

XML





 
Subscription Information:
You can unsubscribe, change your email address, or sign up for any of IT Jungle's free e-newsletters through our Web site at http://www.itjungle.com/sub/subscribe.html.

Copyright © 1996-2008 Guild Companies, Inc. All Rights Reserved.
Guild Companies, Inc., 50 Park Terrace East, Suite 8F, New York, NY 10034

Privacy Statement