Download - Introduction to Ajax - rpgworld.com - AJAX Introduction.pdf · zAJAX uses CGI-style HTTP Requests zUtilizing JavaScript's XMLHttpRequest object zAJAX requests can leverage RPG routines

Transcript
Page 1: Introduction to Ajax - rpgworld.com - AJAX Introduction.pdf · zAJAX uses CGI-style HTTP Requests zUtilizing JavaScript's XMLHttpRequest object zAJAX requests can leverage RPG routines

Introduction to Ajax

with Bob Cozzi

What is AJAX?

Asynchronous JavaScript and XMLA J a X

Asynchronous data retrieval using the XMLHttpRequest object from JavaScript

Data is retrieved from the server as XML, HTML, or JavaScript or plain text.

Dynamically updating the existing web page

Using JavaScript to bring everything together

AJAX is a collection of TechniquesTechniques that leverage existing/available technology

Page 2: Introduction to Ajax - rpgworld.com - AJAX Introduction.pdf · zAJAX uses CGI-style HTTP Requests zUtilizing JavaScript's XMLHttpRequest object zAJAX requests can leverage RPG routines

What AJAX isn't

AJAX is NOT a programming language

AJAX is not an add-on or plug-in

AJAX is not based on JAVA

AJAX is not owned by any Vendor

You can't but some AJAX

Ajax History

AJAX techniques were first used as early as 1998Sometimes formerly called Dynamic HTMLAlthough some people put iFrame back to 1995

February 2005, Jesse James Garrett of Adaptive PathHis now infamous article where he coined the term AJAX

http://adaptivepath.com/publications/essays/archives/000385.php

AJAX technology came into vogue as a result ofGarrett's articleGoogle's use of AJAX in everything they do and their huge success with itBroadband bandwidth usage has increased beyond dial-up

Without Broadband, AJAX would be possible, but not practical nor pervasiveWithout AJAX, Google could not have been as successful

You'd never see Google Maps if only dial-up speeds existed

Page 3: Introduction to Ajax - rpgworld.com - AJAX Introduction.pdf · zAJAX uses CGI-style HTTP Requests zUtilizing JavaScript's XMLHttpRequest object zAJAX requests can leverage RPG routines

Traditional Web Applications

A traditional web application works like this: A web page is displayedThe user enters some data

Whether this means clicking here and there or physically typing in the data—it's all the same

The user presses Enter or clicks the SUBMIT buttonThe server does some processing

Validating the user's dataSearching the databaseCalling legacy programsGenerating an HTML page

The browser is routed to a new HTML pageThe user continues their experience

Web page 1

Server Req 1

Server Req 2

Web page 2

Web page 3

Traditional Web App Flow

Page 4: Introduction to Ajax - rpgworld.com - AJAX Introduction.pdf · zAJAX uses CGI-style HTTP Requests zUtilizing JavaScript's XMLHttpRequest object zAJAX requests can leverage RPG routines

Server Req

Page 2

Time Between Host Server Calls and New Pages

Server Req

Page 1 Page 3

Wait

Server Request

AJAX Eliminates Page Lag

AJAX applications are more like 5250 applicationsA single screen or "page" is used and updated for user interaction

Asynchronous calls mean users continue with what they are doing

Server Request

Server Request

Server Request…

Web Page

Page 5: Introduction to Ajax - rpgworld.com - AJAX Introduction.pdf · zAJAX uses CGI-style HTTP Requests zUtilizing JavaScript's XMLHttpRequest object zAJAX requests can leverage RPG routines

AJAX Plays Nice with RPG IV

AJAX uses CGI-style HTTP RequestsUtilizing JavaScript's XMLHttpRequest object

AJAX requests can leverage RPG routinesThese routines are often small because they are responding to a single or simple request

Give me a list of customers that being with the letter "G"Give me the price for this item number

Handling multiple/different AJAX requests in the same RPG program is common and acceptable

Calling a back-end routine, or a legacy app is also okay.AJAX requests are Asynchronous

Your end-users aren't kept waiting.But watch out "reverb"

Why is AJAX Popular?

Zero FootprintNothing to buy or installIt is completely free and available

No plug-ins requiredNo ActiveX controlsNo Java AppletsNo "waiting for plug-in to download" annoyancesNo "right-click to allow this plug-in to be installed" messages

Provides the capabilities formerly available only throughActiveX controlsJava Applets or plug-insServer-side Scripting, such as JSPs

Page 6: Introduction to Ajax - rpgworld.com - AJAX Introduction.pdf · zAJAX uses CGI-style HTTP Requests zUtilizing JavaScript's XMLHttpRequest object zAJAX requests can leverage RPG routines

Why AJAX Now?

The Browser Wars are finally over

The Statuesque of PCs has changedCPUs in most PCs are fast enough

Memory in most PCs is often vast enough

Java has failed to deliver on its promises

JavaScript (i.e., "scripting") must be enabledJavaScript is trusted by most browser users

Bandwidth has become fast enough

AJAX is Available

Ajax-capable browsers everywhere

XMLHttpRequest object is supported in all of themIE version 7 directly supports XMLHttpRequest

IE version 6 support is thorugh MS-proprietary interfaceBut that interface is 100% compatible with XMLHttpRequest

Nothing to buy or install

As a developer, you don't have to install anything on the PC to make your AJAX-based code work

Everything resides on your host system

Page 7: Introduction to Ajax - rpgworld.com - AJAX Introduction.pdf · zAJAX uses CGI-style HTTP Requests zUtilizing JavaScript's XMLHttpRequest object zAJAX requests can leverage RPG routines

AJAX FrameWorks

Commercial (for sale) and Free JavaScript librariesThese libraries are being called "AJAX FrameWorks"Most are no charge to use or deployVendors make their money by selling add-ons

IDE (development environments/plug-ins)Really good addition function

Adobe's Flex – Uses "Flash", but is very cool. Free with chargeable Eclipse plug-in

TIBCO – Okay free/with chargeable pieces DOJO – Cool, lots of "widgets" freeYahoo's AJAX UI Framework (aka "YUI") – Cool and freeMicrosoft's Atlas – Not as interesting as DOJO or YUINone of these require you to buy anything to use them

AJAX FrameWorks Location

Adobe's Flexhttp://www.adobe.com/devnet/flex/Library is freeOptional, chargeable Eclipse plug-in

Yahoo's AJAX UI Framework (aka "YUI") http://developer.yahoo.com/yui/index.htmlCompact, free, but a bit different (in beta today)

TIBCO GI (General Interface)http://www.tibco.com/software/ria/gi_resource_center.jspProbably will have limited appeal

DOJO – Cool, lots of "widgets" freehttp://dojotoolkit.org/Some unusual interfaces

Page 8: Introduction to Ajax - rpgworld.com - AJAX Introduction.pdf · zAJAX uses CGI-style HTTP Requests zUtilizing JavaScript's XMLHttpRequest object zAJAX requests can leverage RPG routines

Ajax Challenges for Programmers

Requires some new knowledgeYou've got to learn JavaScript or VBScript

AJAX Skill PriorityScale is 1 (least valuable) to 10 (most valuable)

CGI Programming Skill(6)Need to write CGI programs that handle AJAX requests

XML Skill(9) – Depending on your Ajax designNeed to format data for return to the BrowserCould use plain text instead of XML

If plain text is used, XML skill requirement drops to the 2 or 3 range

JavaScript Skill(8)Until a few "build it blindfolded" tools come out, you will need to know JavaScript well.The good news is, it is a easy or as complex as you make it

Ajax Challenges for Users

Web Browser applications are being implementedYahoo, Google, MS, all are moving to AJAX in a HUGE way

Web Browser is normally a benign toolClick, take me here.Click, take me there.

Without AJAX you have a 3, 5, 5 scenario to get the data you wantType, click, thinkclick, thinkType, click, thinkclick, thinkType, click, thinkGet Results

With AJAX you have a 3, 1 scenario to get the information you needType, type, type, Enter (or click)Get results

Page 9: Introduction to Ajax - rpgworld.com - AJAX Introduction.pdf · zAJAX uses CGI-style HTTP Requests zUtilizing JavaScript's XMLHttpRequest object zAJAX requests can leverage RPG routines

AJAX with RPG IV

Your User loads your web page

Some data is typed in

You fire off a CGI requestUsing XMLHttpRequest

Your RPG IV program is called

You create some XML text

You send it back to the browser via stdout

Your AJAX routines receive that data

Your end-user's web page is updated

Generated XML Response

Content-type: text/xmlCache-Control: no-cache

<?xml version="1.0" ?><root><USER_MSG>User ID &quot;COZZI&quot; accepted.</USER_MSG><EMAIL_MSG>email address is invalid</EMAIL_MSG><PWD_MSG>Password must be 6 or more characters</PWD_MSG><PWD2_MSG>Confirming password does not match.</PWD2_MSG></root>

These two statements get absorbed by the browser. They are not

available to the AJAX/JavaScript.

The data needs to be identified as an XML

document, including the version number.

The first node in the XML is detected; it along with the matching closing tag

identify the start and end of the XML.

XML data needs to be escaped. This means special characters, such as < & " ' > are converted into symbolic values.

Page 10: Introduction to Ajax - rpgworld.com - AJAX Introduction.pdf · zAJAX uses CGI-style HTTP Requests zUtilizing JavaScript's XMLHttpRequest object zAJAX requests can leverage RPG routines

Responding to AJAX Request

// Write XML response/free

cgiStdOut('Content-type: text/xml\n');cgiStdOut('Cache-Control: no-cache\n\n');cgiStdOut('<?xml version="1.0" ?>\n');cgiStdOut('<root>\n');escapeHTML(usermsg:%Len(%TrimR(usermsg)):usrMsg:%Len(usrMsg));cgiStdOut('<USER_MSG>%s</USER_MSG>\n': %TrimR(usrMsg));cgiStdOut('<EMAIL_MSG>%s</EMAIL_MSG>\n': emailMsg);cgiStdOut('<PWD_MSG>%s</PWD_MSG>\n':pwdmsg);cgiStdOut('<PWD2_MSG>%s</PWD2_MSG>\n': pwd2Msg);

cgiStdOut('</root>\n');

/end-free

The XML version is necessary. But the

"encoding" can cause problems. So leave it off.

The rest of the XML response goes here. This is the real data you're sending

back to the browser.

The Content-Type header should be

"text/xml"All XML needs a root. It can

be named anything you want. It is often ignored by

the JavaScript.

These XML tags identify the element names that contain the data your returning to the

JavaScript in the browser.

Do not Cache the XML otherwise your user may

see the same data over and over again.

What is XMLHttpRequest?

Foundation behind AJAXA JavaScript classCapable of calling the server

Issues standard HTTP requests.

Captures the server's responseRetrieves HTTP responses from the web server.

Operates Asynchronously or SynchronouslyWhen run asynchronously, tasks run in the background of the browser.

Page 11: Introduction to Ajax - rpgworld.com - AJAX Introduction.pdf · zAJAX uses CGI-style HTTP Requests zUtilizing JavaScript's XMLHttpRequest object zAJAX requests can leverage RPG routines

Simple AJAX Scenario

User types in an Account numberAn AJAX request is triggered

Verify the account numberRetrieves the Account Holder's name

If valid account numberAccount holder's name is displayed near the input

If invalid account numberError message is displayed near the input

HTML for Account Input

<input> tag identifies the input field into which the user types the account numberonblur="Validate()" calls the JavaScript function

When the input field "looses focus" e.g., tab, mouse click outside the field.

<span> is a special HTML tagAllows modification of HTML at runtime via JavaScriptAccess to <span> tags is accomplish via the ID name.This is where the new text or account info is inserted

<input type="text" name="ACCT" size="16" onblur="Validate()">

<span id="ACCT_MSG"></span>

Page 12: Introduction to Ajax - rpgworld.com - AJAX Introduction.pdf · zAJAX uses CGI-style HTTP Requests zUtilizing JavaScript's XMLHttpRequest object zAJAX requests can leverage RPG routines

Validate the Input using AJAX

Validate() called automatically when OnBlur is triggeredThe data from the ACCT input field is retrievedA url-encoded string is createdThe generic AJAX routine is called

function Validate(){

var acct = document.MYFORM.ACCT.value;var url = "/cgi-bin/CHKACCT?ACCT=" + encodeMe(acct);

GoAjax(url,myCallback);}

A Generic GoAjax Functionvar req;

function GoAjax(url, callBack){

if (window.XMLHttpRequest) { req = new XMLHttpRequest();if (req.overrideMimeType) {

req.overrideMimeType('text/xml');}

} else if (window.ActiveXObject) { try {

req = new ActiveXObject("Msxml2.XMLHTTP");} catch (e) {

try { req = new ActiveXObject("Microsoft.XMLHTTP");

} catch (e) {}}

}

if (!req) {alert('Giving up :( Cannot create instance XMLHttpRequest');return false;

}

req.onreadystatechange = callBack;req.open('POST', url, true);req.send(null);

}

We will review this one section at a time.

Page 13: Introduction to Ajax - rpgworld.com - AJAX Introduction.pdf · zAJAX uses CGI-style HTTP Requests zUtilizing JavaScript's XMLHttpRequest object zAJAX requests can leverage RPG routines

Entering the GoAjax Function

var req;

function GoAjax(url, callBack){

/* Create XMLHttpRequest object *//* Send the request async *.

}

Global variable. Must be declared

outside all functions.

Parameters:

1. The URL

2. A function name

Highlighted Function Variablesvar req;

function GoAjax(url, callBack){

if (window.XMLHttpRequest) { req = new XMLHttpRequest();if (req.overrideMimeType) {

req.overrideMimeType('text/xml');}

} else if (window.ActiveXObject) { try {

req = new ActiveXObject("Msxml2.XMLHTTP");} catch (e) {

try { req = new ActiveXObject("Microsoft.XMLHTTP");

} catch (e) {}}

}

if (!req) {alert('Giving up :( Cannot create instance XMLHttpRequest');return false;

}

req.onreadystatechange = callBack;req.open('POST', url, true);req.send(null);

}

The Global variable "req" is used throughout

the function.

Two parameters are only used within this Function.

Page 14: Introduction to Ajax - rpgworld.com - AJAX Introduction.pdf · zAJAX uses CGI-style HTTP Requests zUtilizing JavaScript's XMLHttpRequest object zAJAX requests can leverage RPG routines

Closer Look at Creating the XMLHttpRequest Object

if (window.XMLHttpRequest) { req = new XMLHttpRequest();if (req.overrideMimeType) {

req.overrideMimeType('text/xml');}

} else if (window.ActiveXObject) { try {

req = new ActiveXObject("Msxml2.XMLHTTP");} catch (e) {try {

req = new ActiveXObject("Microsoft.XMLHTTP");} catch (e) {}

}}

Sending the HTTP Request

req.onreadystatechange = callBack;

req.open('POST', url, true);

req.send(null);

... req = new XMLHttpRequest();

Page 15: Introduction to Ajax - rpgworld.com - AJAX Introduction.pdf · zAJAX uses CGI-style HTTP Requests zUtilizing JavaScript's XMLHttpRequest object zAJAX requests can leverage RPG routines

Closer Look at the open() Function's Parameters

Parameter 1: Method

Parameter 2: URL

Parameter 3: Synchronous/Asynchronous status

req.open('POST', url , true );

Parameter 1:

'POST'

'GET'

Parameter 2:

URL-encoded string

Parameter 3:

true = Asynchronous

false = Synchronous

Helper Function EncodeMe()

Some browsers only support the escape() function

Some browsers support new encoding schemes

encodeMe() checks which one is availableCalls the most appropriate one

Page 16: Introduction to Ajax - rpgworld.com - AJAX Introduction.pdf · zAJAX uses CGI-style HTTP Requests zUtilizing JavaScript's XMLHttpRequest object zAJAX requests can leverage RPG routines

encodeMe() Helper Function

function Validate(){

var acct = document.MYFORM.ACCT.value;var url = "/cgi-bin/CHKACCT?ACCT=" + encodeMe(acct);

GoAjax(url,myCallback);}

function encodeMe(value) {

try {return encodeURIComponent(value);

} catch(e) {return escape(value);

}}

Waiting for the Reply

There is no waiting for an asynchronous replyControl is returned back to the browserThe browser user can keep on working

The web server sends a response to the browserThe state of the response changes

The callback function is automatically evoked

The readyState and status are checked in the callback function

Page 17: Introduction to Ajax - rpgworld.com - AJAX Introduction.pdf · zAJAX uses CGI-style HTTP Requests zUtilizing JavaScript's XMLHttpRequest object zAJAX requests can leverage RPG routines

GoAjax Callback Function

function myCallback() {

if (req.readyState == 4) {

if (req.status == 200) {

parseResponse(req.responseXML);}

}}

readyState0 = uninitialized1 = loading2 = finished loading3 = retrieving data4 = completed

status200 = "OK"404 = "Not Found"50x = "Not Authorized"

XMLHttpRequest is an Object

Objects need to be created or instantiated

Objects contain data

Objects also contain functions

Page 18: Introduction to Ajax - rpgworld.com - AJAX Introduction.pdf · zAJAX uses CGI-style HTTP Requests zUtilizing JavaScript's XMLHttpRequest object zAJAX requests can leverage RPG routines

Object Oriented Programming 101-1

Objects are things that contain dataSimilar to Data Structures

Data Members, Member Variables, PropertiesSimilar to data structure subfields

Methods or Member FunctionsSimilar to subprocedures

(If data structures could contain subprocedures)

Call a method and it operates on the data membersAlthough it may also access other data (e.g. global vars)

Object Oriented Programming 101-2

*MODULE objects are similar to OO objects

Global variables are like data members

Subprocedures are like methods

*MODULE MYSTUFF

D nbr S 7P 0D name S 20A

P GetNameP GetNbr

P SetNameP SetNbr

OBJECT MYSTUFF

int nbrchar name[20]

function GetNamefunction GetNbr

function SetNamefunction SetNbr

Similar

Page 19: Introduction to Ajax - rpgworld.com - AJAX Introduction.pdf · zAJAX uses CGI-style HTTP Requests zUtilizing JavaScript's XMLHttpRequest object zAJAX requests can leverage RPG routines

XMLHttpRequest Object Data Members ("Properties")

The XML document (DOM-compatible) returned from the CGI program to the Browser.

responseXML

The text returned from the CGI program to the Browser.responseText

The HTTP status code in textual form. If status is 200, then statusText is "OK". If status is 404, then statusText is "Not found".

statusText

The HTTP status code. For example 200, 404, 500, etc.status

The state of the XMLHttpRequest object.0 = uninitialized1 = loading2 = finished loading3 = interactive4 = completed

readyState

The name of the function that is called when the state of the XMLHttpRequestchanges.

onreadystatechange

DescriptionProperty

XMLHttpRequest Object Methods

Sets the HTTP header to the indicated value.setRequestHeader("label", "value")

Sends the data (if any) by issuing the HTTP request.send( "content" | null )

Identifies the method, URL and async flag for the HTTP request. In addition, the USER ID and Password (if signonis required) may also be specified.

open("method", "URL", async, "userid", "pwd")

Retrieves the value for the specific HTTP header.getResponseHeader( "header" )

Retrieves all HTTP headers and header values.getAllResponseHeaders()

Cancels the current XMLHttpRequest.abort()

DescriptionMethod

Page 20: Introduction to Ajax - rpgworld.com - AJAX Introduction.pdf · zAJAX uses CGI-style HTTP Requests zUtilizing JavaScript's XMLHttpRequest object zAJAX requests can leverage RPG routines

Receiving the Response

Member variable contains callback nameName of function to call when server replies

XMLHttpRequest::onreadystatechange

Function is called when Ready State changesXMLHttpRequest::readyState

Callback should check two member variablesXMLHttpRequest::readyState = 4

XMLHttpRequest::status = 200

Remember Calling GoAjax?

The function name is literally "myCallback"

It could be any name we want

function Validate(){

var acct = document.MYFORM.ACCT.value;var url = "/cgi-bin/CHKACCT?ACCT=" + encodeMe(acct);

GoAjax(url,myCallback);}

The name of a function to call when

the readyStatechanges.

Page 21: Introduction to Ajax - rpgworld.com - AJAX Introduction.pdf · zAJAX uses CGI-style HTTP Requests zUtilizing JavaScript's XMLHttpRequest object zAJAX requests can leverage RPG routines

Remember the GoAjax Function?function GoAjax(url, callBack){

if (window.XMLHttpRequest) { req = new XMLHttpRequest();if (req.overrideMimeType) {

req.overrideMimeType('text/xml');}

} else if (window.ActiveXObject) { try {

req = new ActiveXObject("Msxml2.XMLHTTP");} catch (e) {

try { req = new ActiveXObject("Microsoft.XMLHTTP");

} catch (e) {}}

}if (!req) {

alert('Giving up :( Cannot create instance XMLHttpRequest');return false;

}

req.onreadystatechange = callBack;req.open('POST', url, true);req.send(null);

}

req.onreadystatechange = callBack;

The Callback Function

function myCallback() {

if (req.readyState == 4) {if (req.status == 200) {

parseResponse(req);}

}}

req.onreadystatechange = callBack;

Remember, this is a variable containing the name of the

callback function.

First we check the readyState. Has it

completed?

If completed, we check status. Did the server respond with an "OK" message?

Finally, we call our routine to process the data sent back via the response to

the XMLHttpRequest.

onreadystatchange

contains the name "myCallback"

Page 22: Introduction to Ajax - rpgworld.com - AJAX Introduction.pdf · zAJAX uses CGI-style HTTP Requests zUtilizing JavaScript's XMLHttpRequest object zAJAX requests can leverage RPG routines

Responder Source

function myCallback() {if (req.readyState == 4) {

if (req.status == 200) {parseResponse( req );

}}

}

function parseResponse(xmlRes){var xmlReply = xmlRes.responseXML;

var msgElem = xmlReply.getElementsByTagName('USER_MSG')[0];

var msgElemNode = msgElem.childNodes[0];

var usrMsg = msgElemNode.nodeValue;

}

Retrieving the Returned Data

Two response properties of XMLHttpRequestXMLHttpRequest::responseText

Plain text responses

XMLHttpRequest::responseXMLXML DOM based responses

responseText is plain textYou write a routine to process it as needed

responseXML is an XML DOMUse JavaScript's DOM interfaces to retrieve the data from within the XML

Page 23: Introduction to Ajax - rpgworld.com - AJAX Introduction.pdf · zAJAX uses CGI-style HTTP Requests zUtilizing JavaScript's XMLHttpRequest object zAJAX requests can leverage RPG routines

Response Handling Function

function parseResponse(xmlRes){var xmlReply = xmlRes.responseXML;

var msgElem = xmlReply.getElementsByTagName('USER_MSG')[0];

var msgElemNode = msgElem.childNodes[0];

var usrMsg = msgElemNode.nodeValue;

}

Response Handling Function

function parseResponse(xmlRes){

var xmlReply = xmlRes.responseXML;var msgElem = xmlReply.getElementsByTagName('USER_MSG')[0];var msgElemNode = msgElem.childNodes[0];

var usrMsg = msgElemNode.nodeValue;

var usrDiv = document.getElementById("USER_MSG");

if (usrMsg) {usrDiv.innerHTML = "<span style=\"color:red\">"+ usrMsg +"</span>";

}else usrDiv.innerHTML = "No user msg";

}

<input type="text" name="USERID" size="16" onblur="Validate()">

<span id="USER_MSG"></span>

XML

tag

nam

e

SPAN identifier

Page 24: Introduction to Ajax - rpgworld.com - AJAX Introduction.pdf · zAJAX uses CGI-style HTTP Requests zUtilizing JavaScript's XMLHttpRequest object zAJAX requests can leverage RPG routines

What does it look like?

User Interface is controlled dynamicallyKeystroke/mouse action event handlingNo waiting for an "Enter" key to react

Immediate validation/feedback of actionsSingle-page interface is more familiar

With traditional/5250 business applications

What do I think about AJAX?