Asynchronous JavaScript And XML (AJAX) Asst. Prof. Dr. Kanda - - PowerPoint PPT Presentation

asynchronous javascript and xml ajax
SMART_READER_LITE
LIVE PREVIEW

Asynchronous JavaScript And XML (AJAX) Asst. Prof. Dr. Kanda - - PowerPoint PPT Presentation

Asynchronous JavaScript And XML (AJAX) Asst. Prof. Dr. Kanda Runapongsa Saikaew (krunapon@kku.ac.th) Dept. of Computer Engineering Khon Kaen University 1 What is Common of these? Web sites Google Maps http://maps.google.com


slide-1
SLIDE 1

1

Asynchronous JavaScript And XML (AJAX)

  • Asst. Prof. Dr. Kanda Runapongsa Saikaew

(krunapon@kku.ac.th)

  • Dept. of Computer Engineering

Khon Kaen University

slide-2
SLIDE 2

What is Common of these?

Web sites

Google Maps http://maps.google.com Google Mail http://gmail.google.com Google Search http://www.google.com Flicks Photo Sharing http://flickr.com Social Bookmarking http://del.icio.us

2

slide-3
SLIDE 3

Google Search with AJAX

3

slide-4
SLIDE 4

4

Agenda

 What is AJAX?  Why AJAX?  The Rise of AJAX  AJAX Characteristics AJAX Technologies  AJAX Design

slide-5
SLIDE 5

What is AJAX?

AJAX: Asynchronous Javascript And

XML

An architectural style (a high level

design pattern) for creating interactive web applications

Make the Web become richer and

response, closing the gap with the desktop

5

slide-6
SLIDE 6

Why AJAX?

 HTTP never intend to dynamically

serve content

Pages always reload, but never get

updated

Users wait for the entire page to load

even if a single piece of data is needed

Single request/response restrictions

No middle ground between “this page”

and “next page”

6

slide-7
SLIDE 7

Why Web Application? (1/5)

People are using different computers

at home, at work, at school, in cafes, and on their phones

Hosting the data online is the most

natural way

Some people have no computer

A web application is the only practical

way to use a particular application and safely retain all their data

7

slide-8
SLIDE 8

Why Web Application? (2/5)

Many homes and offices now have

broadband and server hardware is more powerful than ever

Server-side storage is cheap enough for

vast amounts of data to be held online

The technologies behind AJAX –

JavaScript, the DOM, and Web remoting have matured and become more standard

8

slide-9
SLIDE 9

Why Web Application? (3/5)

For developers, a modern web

application is more productive than a conventional GUI alternative

A single set of code for all platforms Allow upgrade the application

incrementally

Choose whatever programming

languages and libraries they want to work with

9

slide-10
SLIDE 10

Why Web Application? (4/5)

Developing rich applications on the

Web used to be considered a kind of rocket science

But it‟s actually a lot easier now to

develop for the Web – arguably easier than many GUI environments

As security concerns have

heightened, companies are now quicker to lock down desktops and forbid browser plugins

10

slide-11
SLIDE 11

Why Web Application? (5/5)

Application developers are usually

interesting in supporting as wide a user base as possible

A web application is often more a

flexible way to target these newer platforms

One of the great strengths of the

Internet is the ability to communicate and collaborate wit remote users

11

slide-12
SLIDE 12

AJAX: Change in Real-time

They let you drag boxes instead of

clicking on arrows and typing in numbers

They keep page content fresh instead

  • f forcing you to keep hitting Refresh

button

They show meaningful animations

instead of verbose messages

12

slide-13
SLIDE 13

The Rise of AJAX

On February 18, 2005, Jesse-James

Garrett published an online article “Ajax: A New Approach to Web Applications”

Garrett introduced “Ajax to label the

architecture behind the new generation of rich web applications like google Maps and Google Suggest

13

slide-14
SLIDE 14

AJAX Characteristics (1/3)

Applications, Not Just Web sites

Keeps user engaged and productive Socialize via the browser platform

Smooth, Continuous Interactions

JavaScript makes AJAX interaction feel

faster and more continuous

Live

Can be programmed to always show the

latest news, details on who else is

  • nline, or to send messages to the user 14
slide-15
SLIDE 15

AJAX Characteristics (2/3)

 Supportive

 AJAX Apps can monitor user actions and

proactively support whatever task the user‟s working on

 Visual Effects

 Animation that gets across a message about

what‟s happening and what the user can do next

 Standards-based

 AJAX makes the most of standard browser

features and avoid browser-specific features and plugins where possible

15

slide-16
SLIDE 16

AJAX Characteristics (3/3)

New Widgets

AJAX Widgets go beyond the standard

HTML controls

Sliders and progress indicators, built on

standard HTML elements, are becoming popular

New Styles of Interaction

Drag-and-drop Keyboard shortcuts

16

slide-17
SLIDE 17

AJAX Technologies

Standards-based presentation using

XHTML and CSS

Dynamic display and interaction using

DOM

Data interchange and manipulation

using XML and XSLT

Asynchronous data retrieval using

XMLHttpRequest

JavaScript binding everything

together

17

slide-18
SLIDE 18

HTML/XHTML

An AJAX App uses an HTML

document to show the initial page

The document is continuously

manipulated to change the display and set up new events

Where possible, its XML-compliant

variant, XHTML, should be used in

  • rder to make manipulation more

robust

18

slide-19
SLIDE 19

CSS

CSS enriches the display and, thanks

to stylesheets, helps separate document structure from style details

CSS can easily be manipulated with

JavaScript

With just one line of code, you can

make an object disappear, move it around the page, or alter its appearance

19

slide-20
SLIDE 20

HTTP, CGI, Form Submission

AJAX communicates via HTTP Instead of returning full pages, the

server returns concise results that are then processed in the browser script

Form submission is also used, no

page refresh need take place

20

slide-21
SLIDE 21

Server-Side Scripting

The server is still required to perform

tasks like data persistence and input validation

In some AJAX applications, it no

longer performs any duty of display or application logic

Leaving those things for the browser

script to handle

21

slide-22
SLIDE 22

JavaScript

Client-side programming language

that coordinates browser activity

Not Java, but from the same family

Java-like syntax Loosely-typed variables, dynamically

interpreted

Functions are objects

Can be involved from outside a class

Can use OOP-like style, but not

required

22

slide-23
SLIDE 23

DOM

The DOM exposes a web page to the

JavaScript engine

Programming recommendations

Use of “id” attribute to make finding

elements easy

CSS styles applied using node‟s

className attribute

Head1.className = „redhead‟;

Use of XHTML

23

slide-24
SLIDE 24

Asynchronous Data Loading (1/2)

Two techniques: IFrames,

XMLHTTPRequest

Iframes (Inline Frames) are an old

technique given new life with AJAX

Invisible frame, in line with other

HTML

IFrame owns the processing

24

slide-25
SLIDE 25

Asynchronous Data Loading (2/2)

XMLHttpRequest: DOM extensions

allowing asynchronous calls

Issues: browser compatibility

Developer owns implementation, testing

burden …

Example: some web page displays

successfully with IE but not with Firefox

25

slide-26
SLIDE 26

Classic vs. AJAX Application Model

26

slide-27
SLIDE 27

Synchronous vs. Asynchronous

27

slide-28
SLIDE 28

AJAX Design Principles (1/2)

The browser hosts an application, not

content

Application code delivered to the

browser, mostly as JavaScript code

The server delivers data, not content

Data may be plain text, JavaScript

fragments, or XML documents

28

slide-29
SLIDE 29

AJAX Design Principles (2/2)

User/application interaction is

continuous and fluid

UI methapors like drag-and-drop

become possible

This is real coding and requires

discipline

Significant developer responsibility to

manage conversational state over entire web transaction

29

slide-30
SLIDE 30

Why is it Popular?

Google helped popularize, and

legitimize it in Gmail

Increase usability of Web applications Rich Internet applications without

Flash

Save bandwidth Download only data you need Faster interfaces (sometimes)

30

slide-31
SLIDE 31

AJAX Downsides (1/2)

Note these are not all specific to

AJAX

Browser “back” button may not work

Browsers record static page visits

Increase browser code size

Response time affected

Difficult to debug

Processing logic both in client

31

slide-32
SLIDE 32

AJAX Downsides (2/2)

 Bookmarking state becomes difficult

 JavaScript generates the page

 Viewable source

 Open to hackers or plagiarism

 Server Load

 Asynchronous request may be an expensive

  • peration

 Web analytics

 Many web analytics solutions are based on

the paradigm of a new page being loaded whenever new content is displayed to the user

32

slide-33
SLIDE 33

AJAX Toolkits

 Dojo Toolkit  http://dojotoolkit.org/  Google Web Toolkit  http://code.google.com/webtoolkit/  PHP Ajax Frameworks  http://ajaxpatterns.org/PHP_Ajax_Frameworks  AJAX : The Official Microsoft ASP.NET Site  http://www.asp.net/ajax/  Prototype JavaScript Framework  http://prototypejs.org/

33

slide-34
SLIDE 34

Technologies Used in AJAX (1/2)

Javascript

Loosely typed scripting language JavaScript function is called when an

event in a page occurs

Glue for the whole AJAX operation

DOM

Represents the structure of XML and

HTML documents

API for accessing and manipulating

structured documents

34

slide-35
SLIDE 35

Technologies Used in AJAX (2/2)

CSS

Allows for a clear separation of the

presentation style from the content and may be changed programmatically by JavaScript

XMLHttpRequest

JavaScript object that performs

asynchronous interaction with the server

35

slide-36
SLIDE 36

What is XMLHttpRequest?

JavaScript object Adopted by modern browsers

Mozilla™, Firefox, Safari, and Opera

Communicates with a server via

standard HTTP GET/POST

XMLHttpRequest object works in the

background for performing asynchronous communication with the backend server

Does not interrupt user operation

36

slide-37
SLIDE 37

Steps of AJAX Operation

  • 1. A client event occurs

2.An XMLHttpRequest object is created 3.The XMLHttpRequest object is configured 4.The XMLHttpRequest object makes an

  • async. request

5.The ValidateServlet returns an XML document containing the result 6.The XMLHttpRequest object calls the callback() function and processes the result 7.TheHTML DOM is updated

37

slide-38
SLIDE 38

XMLHttpRequest Methods

 open(“HTTP method”, “URL”, syn/asyn):

Assigns HTTP method, destination URL, mode

 send(content): Sends request including string

  • r DOM object data

 abort(): Terminates current request  getAllResponseHeaders(): Returns

headers (labels + values) as a string

 getResponseHeader(“header”): Returns

value of a given header

 setRequestHeader(“label”,”value”): Sets

Request Headers before sending

38

slide-39
SLIDE 39

XMLHttpRequest Properties

 Onreadystatechange

 Set with an JavaScript event handler that fires

at each state change

 readyState – current status of request

 0 = The request is not uninitialized  1 = The request has been loading  2 = The request has been loaded  3 = The request is in process  4 = The request is complete

 Status

 HTTP Status returned from server: 200 = OK 39

slide-40
SLIDE 40

XMLHttpRequest Properties

responseText

String version of data returned from the

server

responseXML

XML document of data returned from the

server

statusText

Status text returned from server

40

slide-41
SLIDE 41

Using the readyState Property

xmlHttp.onreadystatechange=function() { if(xmlHttp.readyState==4) { // Get the data from the server's response } }

41

slide-42
SLIDE 42

AJAX Sample1 Application (1/8)

1. 1.

A Client t event t occurs rs // file display.html <html><head> <script src="clienthint.js"></script> </head> <body> <form> Company Name : <input type="text" id="txt txt1"onke keyu yup="sh showH wHin int(th this. is.va value)"> </form> <p><span id="txtHint"> Result will be list here.</span></p> </body></html>

42

slide-43
SLIDE 43

AJAX Sample1 Application (2/8)

  • 2. An XMLHtt

ttpReq Request st object ct is create ted //clienthint.js (1/4) var xmlHttp function showHint(str) { if (str.length==0) { document.getElementById("txtHint").innerHTML=""; return; } xmlHttp Http=Ge GetX tXmlHtt lHttpOb Obje ject() ct() if (xmlHttp==null) { alert ("Your browser does not support AJAX!"); return; }

43

slide-44
SLIDE 44

AJAX Sample1 Application (3/8)

 3. An XMLHttpR

pRequ eques est object is configured igured with h a callback lback function ion

 4. XMLHttpReques

pRequest object ect makes es an async nc. request uest

 //clienthint.js (2/4)

var url="getDa getData. a.php"+"?q= php"+"?q="+str+ r+"&s &sid="+ id="+ Math. h.rand random

  • m();

(); // result from calling stateChanged function xmlHttp.onready lHttp.onreadystat atec echange hange=s =stat ateC eChan hanged; ged; xmlHtt lHttp.open("G p.open("GET",url, url,true); rue); xmlHtt lHttp.sen p.send(null); d(null); }

44

slide-45
SLIDE 45

AJAX Sample1 Application (4/8)

//clienthint.js (3/4) function GetXmlHttpObject(){ var xmlHttp=null; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; }

45

slide-46
SLIDE 46

AJAX Sample1 Application (5/8)

  • 6. XMLHttpReques

pRequest object ect call lls call llbac ack() () function n and proces esses es the result lt

 The XMLHttpRequest object was configured to

call the stateChanged() function when there is a state change to the readyState of the XMLHttpRequest object

 7. The HTML DOM is updated

function stateChanged() { if (xmlHttp. p.readySt readyState== ate==4) ) { document ument.getEl getElem ementBy entById("txtH d("txtHint int") .innerHTML=xmlHttp.responseText; }}

46

slide-47
SLIDE 47

AJAX Sample1 Application (6/8)

<!-- getData.php (1/3) --> <?php // Connect to database and fetch result into array name. $name = array("Amazon 24689", "Google 13579", "Holiday Inn 123456", "Bevery Hills 987665", "Rhyme & Reason Inc. 966640", "RRR Advertising Inc. 466136", "RIVIERA HOTELS 169706", "RIVIERA HOTELS 928748", "RRR Advertising Inc. 77165", "Yahoo Inc. 369864"); $q=$_GET["q"]; // get the q parameter from URL

47

slide-48
SLIDE 48

AJAX Sample1 Application (7/8)

<!-- getData.php (2/3) --> //lookup all hints from array if length of q>0

  • 5. The Sereer-side

ide script t returns ns the resul ults ts if (strlen($q) > 0){ $hint=""; for($i=0; $i<count($name); $i++) { if (strtolower($q)==strtolower(substr($name[$i],0,strlen($q)))) { if ($hint=="") { $hint=$name[$i]; } else { $hint=$hint."<br/>".$name[$i]; } } } }

48

slide-49
SLIDE 49

AJAX Sample1 Application (8/8)

<!-- getData.php (3/3) --> //Show Hint if ($hint == ""){ $response="Not found!"; } else{ $response=$hint; } //output the response echo $response; ?>

49

slide-50
SLIDE 50

View display.html on Firefox

50

slide-51
SLIDE 51

View display.html on IE

51

slide-52
SLIDE 52

Dojo and JSON

To build AJAX applications, we can

choose to write our own verbose JavaScript code or use already tested and functional libraries

Dojo and JSON are two very different

but complementary technologies

Both of them can significantly

enhance the interface and usability of web applications

52

slide-53
SLIDE 53

What is Dojo?

 Dojo is a set of powerful Javascript

libraries that provide a simple API to a plethora of features

 Aside from providing Ajax functionality,

Dojo also provides packages for

 String manipulation  DOM manipulation  Drag-and-drop support  Data structures, such as lists, queues, and

stacks

53

slide-54
SLIDE 54

What is JSON?

JSON is a Java library that helps

convert Java objects into a string representation

JSON is designed to be used in

conjunction with JavaScript code making HTTP requests

Since server side can be written in a

variety of languages such as C#, Python, PHP, and Java

54

slide-55
SLIDE 55

Development Tools on Mozilla Browser

 Mozilla FireBug debugger (add-on)

 This is the most comprehensive and most useful

JavaScript debugger

 This tool does things all other tools do and more

 Mozilla JavaScript console  Mozilla DOM inspector (comes with Firefox

package)

 Mozilla Venkman JavaScript debugger (add-on)  Mozilla LiveHTTPHeaders HTTP monitor

(similar to NetBeans HTTP monitor)

55

slide-56
SLIDE 56

Mozilla FireBug Debugger

 Spy on XMLHttpRequest traffic  JavaScript debugger for stepping through code one

line at a time

 Inspect HTML source, computed style, events, layout

and the DOM

 Status bar icon shows you when there is an error in a

web page

 A console that shows errors from JavaScript and CSS  Log messages from JavaScript in your web page to

the console (bye bye "alert debugging")

 An JavaScript command line (no more "javascript:" in

the URL bar)

56

slide-57
SLIDE 57

References (1/2)

 Wikipedia, “Ajax (programming)”,

http://en.wikipedia.org/wiki/Ajax_(program ming)

 UW Business School, “AJAX Overview”,

http://faculty.washington.edu/rfish/msis531 /lectnote/3up/ajax.pdf

 Jesse-James Garrett, “Ajax: A New

Approach to Web Applications”, http://www.adaptivepath.com/publications/ essays/archives/000385.php

57

slide-58
SLIDE 58

References (2/2)

 Zarar Siddiqi, “Using Dojo and JSON to

Build AJAX Applications”, http://today.java.net/pub/a/today/2006/04/27/ building-ajax-with-dojo-and-json.html

 Michael Mahemoff, “Ajax Design

Patterns”, O‟Reilly, June 2006

58