43
© Rizwan Ahmed 2008 AJAX: The New Paradigm for Enterprise Web Applications Rizwan Ahmed

Ajax

Embed Size (px)

Citation preview

Page 1: Ajax

© Rizwan Ahmed 2008

AJAX: The New Paradigm for Enterprise

Web Applications

Rizwan Ahmed

Page 2: Ajax

2

What is AJAX?

New approach to web interaction Involves transmitting only small amounts of

information to and from server Gives user the most responsive experience Traditional web app model – browser initiates

requests and processes HTML response AJAX model provides an intermediate layer –

AJAX Engine to handle this communication

Page 3: Ajax

3

Components of AJAX

Asynchronous data retrieval using XMLHttpRequest

Data interchange and manipulation using XML, XPath and XSLT

Dynamic display and interaction using the Document Object Model

Standards based presentation using XHTML and CSS

JavaScript binding everything together

Page 4: Ajax

4

Characteristics of AJAX apps

Continuous Feel Real-Time updates Established Standards Non proprietary Language Neutrality XML declarative interface Non Browser specific

Page 5: Ajax

5

AJAX Model

Page 6: Ajax

6

Sequences of AJAX vs. Traditional web model

Page 7: Ajax

7

Who is using AJAX?

Yahoo! Web Search

Page 8: Ajax

8

Who is using AJAX?

Google Maps

Page 9: Ajax

9

Who is using AJAX?

Yahoo! News

Page 10: Ajax

10

Beneath the Hood

At the very core of any AJAX app:

Request variable in JavaScript instantiated with one of the following methods:

ActiveXObject(“Microsoft.XMLHTTP”) for IE 6 browsers

XMLHttpRequest Object for all others IE 7+ will have native XMLHttpRequest

support

Page 11: Ajax

11

XMLHttpRequest

A JavaScript class built into the browser that lets you make Asynchronous HTTP requests

Class is instantiated by custom JavaScript code triggered from HTML events

A Forward URL string representing the server resource is included with each call

A Call Back JavaScript function is invoked depending on the state of the HTTP Response

Page 12: Ajax

12

XMLHttpRequest Properties

onreadystatechange – informs Ajax engine that response is ready for call back function

readyState – current state of the HTTP call responseText – the text result of the request responseXML – DOM XML object result of the

request status – HTTP status code of the response statusText – HTTP status text

Page 13: Ajax

13

XMLHttpRequest Example

var key = document.getElementById("key");

var url = "/server/resource?key="+key.value;

if (window.XMLHttpRequest) {

req = new XMLHttpRequest();

}

req.open("Get",url,true);

req.onreadystatechange = callback;

req.send();

Page 14: Ajax

14

Server Resource

public class ServerResourceServlet extends HttpServlet { public void doGet(req, res) { String key = req.getParameter("key"); ……. if (key != null) { returnXML = new StringBuffer("\r\n<returnedData>"); returnXML.append(…); returnXML.append("\r\n</returnedData>"); // setup the response res.setContentType("text/xml"); // write out the xml string res.getWriter().write(returnXML.toString()); } }}

Page 15: Ajax

15

Callback

Callback can be either discrete functions or anonymously declared.

function callback(){ if (req.readyState==4){ if (req.status == 200){ modifyHTML(…); } } clear(); }

Page 16: Ajax

16

Mining the Response

function modifyHTML(){ var resp = req.responseText; var parser = new DOMParser(); var dom = parser.parseFromString(resp);

var val = dom.getElementsByTagName(..); var elemId = document.getElementbyId(..); elemId.value = val[0].childNodes[0].nodeValue;……….}

Page 17: Ajax

17

Cross Browser Compatibility

if (window.XMLHttpRequest) {

req = new XMLHttpRequest();

} else if (window.ActiveXObject) {

try {

req = new ActiveXObject(Msxml2.XMLHTTP);

} catch (Exception e) {

req = new ActiveXObject(Microsoft.XMLHTTP); }

}

Page 18: Ajax

18

Data Vehicles

● XML

<returnedData> <zip>29203</zip> <city>Columbia</city> <state>SC</state></returnedData>

● Plain Text (Custom formatted eg. CSV, HTML) returnedData;29203;Columbia;SC

Page 19: Ajax

19

Data Vehicles (cont.)

● JavaScript Object Notation (JSON)

A lightweight data format based off the JavaScript syntax. Definitions can be included and parsed with JavaScript.

{“returnedData”:{ “zip”: “29203”, “city”: “Columbia”, “state”: “SC”}}

Page 20: Ajax

20

Some AJAX Libraries

● DoJo Toolkit (http://dojotoolkit.org/)

● Rico Toolkit (http://openrico.org/)

● DWR Toolkit (http://getahead.org/dwr/)

● Prototype (http://prototypejs.org)

● AjaxTags (http://ajaxtags.sourceforge.net)

Page 21: Ajax

21

AJAX Libraries (cont.)

DoJo Toolkit

● DoJo is an open source DHTML toolkit written in JavaScript and include the AJAX specific libraries dojo.io; dojo.rpc; dojo.json

var key = document.getElementById("key"); dojo.io.bind({ url: "/server/resource?key="+key.value, load: function(type, data, evt) { callback(data); }, error: function(type, data, evt) { reportError(data); }, mimetype: “text/plain” });

Page 22: Ajax

22

AJAX Libraries (cont.)

Rico ToolkitRico is an open source toolkit allows for registering AJAX request handlers and HTML elements as AJAX response objects● ajaxEngine.registerElement(‘rHdl’,’server url’) ajaxEngine.sendRequest(‘rHdl’,’key=‘+key.value)

● Server resource must respond with XML formatted document. Rico matches id attributes in the document with fields in the HTML form and populates it accordingly

● No callback functions are necessary

Page 23: Ajax

23

AJAX Libraries (cont.)

DWR ToolkitDirect Web Remoting is an open source AJAX framework for Java/JSP● DWRServlet on the server end runs the whole show. Instantiated during application load time

● On browser side a JavaScript wrapper library is created using Java’s Reflections API that mirror the server side classes

● An XML configuration file dwr.xml provides the plumbing that connects the server side classes with the JavaScript

Page 24: Ajax

24

AJAX Libraries (cont.)

Prototype Framework● Prototype is another open source framework that does AJAX requests with browser differences abstracted from user

parameterString = “key=" + escape(key); new Ajax.Request(“/server/resource", { method: "get", parameters: parameterString, onSuccess: function(request) { var result = request.responseText; ….. }, onFailure: function(request) {…...} });

Page 25: Ajax

25

AJAX Libraries (cont.)

Prototype Framework (cont.)● Prototype includes enhanced library support for JSON, DOM and other utilities

● Prototype is largely used in conjunction with scriptaculous

● Scriptaculous toolkit provides easy to use, cross browser JS libraries. Includes animation framework, visual effects, drag and drop features and AJAX controls

Page 26: Ajax

26

AJAX Libraries (cont.)

AJAX using Custom Tags● Writing Ajaxian code over and over can be tedious and error prone

● Encapsulate the functionality into a custom JSP tag for easy reuse

● Using Tag Libraries will save time and enhance reusability and maintainability of the code

● Consists of a TLD and Tag Support class

● There are a number of 3rd party Tags that encapsulate Ajaxian functionality

Page 27: Ajax

27

AJAX Libraries (cont.)

AjaxTags

● AjaxTags is a Sourceforge project. Allows use of AJAX with minimal effort● Consists of the following representative tags:

Autocomplete – Displays list of entries that match text into the autocomplete field HTML Content Replace - Connects a content area to an HTML onclick event Portlet – Adds a portlet to a JSP page Select/Dropdown – Populates a select field based on selection in another select field

Page 28: Ajax

28

AJAX Design Patterns

A. Predictive Fetch

Traditional web solutions – app has no idea what is to come next

Fetch on Demand – User through his actions requests data retrieval

Unfortunate side effect of forcing the start-and-stop model of user interaction upon the user

Page 29: Ajax

29

AJAX Design Patterns

A. Predictive Fetch (cont.)

Guess what the user is going to do next and pre-fetch the appropriate data

Simple use cases where predicting user actions are easier

Anticipate and preload information to make app feel lighter and responsive

Must exercise “logical to assume” criterion

Page 30: Ajax

30

AJAX Design Patterns (cont.)

B. Submission Throttling

In AJAXian apps user interacts with the app by sending async requests

The timing and frequency of sending requests is of paramount importance

One solution would be to send data to server each time a user action occurs

This generates a large number of requests in a short period of time

Page 31: Ajax

31

AJAX Design Patterns (cont.)

B. Submission Throttling (cont.)

Using ST you buffer the data on the client and then send it at pre-determined intervals

Yahoo! and Google search does this

Wait for a certain amt of time and then sends all data in the text box

The delay from typing to sending has been fine tuned

Page 32: Ajax

32

AJAX Design Patterns (cont.)

B. Submission Throttling (cont.)

ST begins when application first loads or a specific user action

Client side function is called to begin the buffering of data

Determination when, what and how much to send depends on use case

May want to send data when it reaches a particular size

Page 33: Ajax

33

AJAX Design Patterns (cont.)

C. Periodic Refresh

Process of checking for new server info at specific intervals – polling

In its simplest form a loop can be established to run indefinitely setInterval(callServer, REFRESH_PERIOD_MILLIS);

Periodic Refresh fakes a back channel situation forcing server data back to client

Page 34: Ajax

34

AJAX Design Patterns (cont.)

C. Periodic Refresh (cont.)

Successfully used by ESPN to update its online scoreboards:

(sports.espn.go.com/nfl/scoreboard)

Page 35: Ajax

35

AJAX Design Patterns (cont.)

C. Periodic Refresh (cont.)

The period between refreshes would ideally be 0. Latency issues.

Entails significant resource cost. Ensure bandwidth and associated infrastructure.

Key design aim must be to increase the average refresh period and reduce content per refresh

Page 36: Ajax

36

AJAX Design Patterns (cont.)

D. Multi-Stage Download

Lasting problems on the web - the speed at which pages download

Residential broadband has caused many sites to increase multimedia content (animation, pictures etc.)

Slower download times as everything is loaded in random order

Page 37: Ajax

37

AJAX Design Patterns (cont.)

D. Multi-Stage Download (cont.)

AJAX pattern where only the basic functionality is loaded initially

The page then begins to download other components that should appear

Popularized by start.com

User driven activity determines content loading behind scenes

Page 38: Ajax

38

AJAX Design Patterns (cont.)

D. Multi-Stage Download (cont.)

Page must work in its simplest form for non-AJAX browsers

Provide “graceful degradation” – those supporting AJAX technologies will get extensive interface while others get the bare bones

Important if you expect search engines to crawl through your web site

Page 39: Ajax

39

Request Management

● Issues related to the frequency and timing of requests

● Major concern is the number of times that communication occurs between client and server

Server can get bogged down while trying to handle multiple user requests

Client can become unresponsive while waiting for server responses

Page 40: Ajax

40

Request Management

● Most browsers have inbuilt queuing mechanisms which is not robust

● Works well when requests are few and far in between

● In real world requests are being sent from various parts of the application at different times

● No control over when requests are sent or what order they should be sent

Page 41: Ajax

41

Request Management (cont.)

● Implement a Priority Queue

Priority based promotion. Values inserted based on request priority.

Age based promotion. Requests bumped up the priority based on age.

RequestManager Object to handle XMLHttpRequest

Page 42: Ajax

42

Recap

What is AJAX Asynchronous data retrieval using XMLHttp Data interchange and manipulation using XML/XPath/XSLT Dynamic display and interaction using DOM Standards based presentation using XHTML and CSS JavaScript binding everything together

Characteristics of AJAX applications Continuous feel/Real Time Updates Established Standards/Language neutrality Dynamic display and interaction using DOM

AJAX Libraries AJAX Design Patterns

Predictive Fetch Submission Throttling Periodic Refresh Multi-Page Download

Page 43: Ajax

43

References

http://ajaxpatterns.org

http://www.w3cschools.com/ajax

http://www.adaptivepath.com/ideas/essays/archives/000385.php - Seminal Article on AJAX

Ajax on Java: Steven Douglas Olson

Professional AJAX: Zakas, McPeak, Fawcett