iat352-09-wk11-ajax-web-application0.ppt

30
1 Ajax: A New Approach to Web Applications IAT352 – Spring 2009 Eric Yang School of Interactive Arts and Technology Simon Fraser University Surrey

Transcript of iat352-09-wk11-ajax-web-application0.ppt

Page 1: iat352-09-wk11-ajax-web-application0.ppt

1

Ajax: A New Approach to Web Applications

IAT352 – Spring 2009

Eric YangSchool of Interactive Arts and Technology

Simon Fraser University Surrey

Page 2: iat352-09-wk11-ajax-web-application0.ppt

2

Why Ajax? Question: can web applications be as responsive as

their desktop counterparts? Desktop applications have a richness and responsiveness

that has seemed out of reach on the Web there is a gap With Ajax, the gap is closing Examples of Ajax web applications: everything

Google Suggest everything happens almost instantly, with no waiting for

pages to reload Google Maps

everything happens almost instantly, with no waiting for pages to reload

These great dynamic Web UIs were sufficiently groundbreaking to be dubbed "Web 2.0"

Page 3: iat352-09-wk11-ajax-web-application0.ppt

3

Defining Ajax Ajax: Asynchronous JavaScript & XML

An approach to Web application development that uses client-side scripting to exchange data with the Web server

As a result, Web pages are dynamically updated without a full page refresh interrupting the interaction flow

the immediacy and usability of native desktop applications Ajax is not a technology but a design pattern that based

on the following technical components: XHTML and CSS: for standards-based presentation Document Object Model (DOM): for dynamic display and

interaction XML and XSLT: for data interchange and manipulation XMLHttpRequest: for asynchronous data retrieval JavaScript: binding everything together

Page 4: iat352-09-wk11-ajax-web-application0.ppt

4

Who’s Using Ajax? Google is making a huge investment in developing the Ajax

approach: Gmail Google Groups Google Suggest Google Maps Orkut

Others are following suit: Flickr: many of the features that people love depend on Ajax A9.com: Amazon’s search engine

These projects demonstrate that Ajax is not only technically sound, but also practical for real-world applications

Ajax applications can be any size, from the very simple, single-function Google Suggest to the very complex and sophisticated Google Maps

Page 5: iat352-09-wk11-ajax-web-application0.ppt

5

Traditional model for web applications vs. Ajax model

Traditional: user actions trigger

an HTTP request back to a web server

The server does some processing, and then returns an HTML page to the client

Doesn’t make for a great user experience

Page 6: iat352-09-wk11-ajax-web-application0.ppt

6

Traditional model for web applications vs. Ajax model (2)

User has to wait some time for server when it’s processing user interaction come to a halt every time the application needs something from the server

Page 7: iat352-09-wk11-ajax-web-application0.ppt

7

Traditional model for web applications vs. Ajax model (3)

Ajax: Eliminates the start-

stop-start-stop nature of interaction by introducing an intermediary — an Ajax engine — between the user and the server

Page 8: iat352-09-wk11-ajax-web-application0.ppt

8

Traditional model vs. Ajax model (4) Ajax engine allows the user’s interaction with the

application to happen asynchronously — independent of communication with the server So the user is never staring at a blank browser window and an

hourglass icon, waiting around for the server to do something

Page 9: iat352-09-wk11-ajax-web-application0.ppt

9

Elaboration on Ajax engine

Every user action (that normally would generate an HTTP request to server) would use JavaScript to call Ajax engine instead

Any response to a user action that doesn’t require a trip back to the server, the engine handles on its own e.g. simple data validation, editing data in memory,

and even some navigation If the engine needs something from the server in

order to respond, the engine makes those requests asynchronously e.g. submitting data for processing, loading additional

interface code, or retrieving new data

Page 10: iat352-09-wk11-ajax-web-application0.ppt

10

Moving Forward

The biggest challenges in creating Ajax applications are not technical The core Ajax technologies are mature, stable,

and well understood

The challenges are for the designers of these applications Begin to imagine a wider, richer range of

possibilities

Page 11: iat352-09-wk11-ajax-web-application0.ppt

11

Ajax Case Study:A dynamically updated

Shopping Cart

Page 12: iat352-09-wk11-ajax-web-application0.ppt

12

Topics

Touch on all the tools you need to begin developing your own applications using Ajax

Explain the concepts behind Ajax and demonstrate the fundamental steps to creating an Ajax interface for a Java-based Web application

Use code examples to demonstrate both the server-side Java code and the client-side JavaScript that make Ajax applications so dynamic

Page 13: iat352-09-wk11-ajax-web-application0.ppt

13

A Better Shopping Cart

A simple example of a shopping cart that is dynamically updated as items are added to it Download the source code by clicking here This approach would let users continue browsing

and adding items to their carts without having to wait after each click for a full-page update

While some of the code shown here is specific to the shopping cart example, the techniques illustrated can be applied to any Ajax application

Page 14: iat352-09-wk11-ajax-web-application0.ppt

14

Listing 1: the HTML code the shopping-cart example uses

Page 15: iat352-09-wk11-ajax-web-application0.ppt

15

The Ajax Roundtrip An Ajax interaction begins with a JavaScript object called

XMLHttpRequest The first step in this Ajax roundtrip is to create an

XMLHttpRequest instance It allows a client-side script to perform HTTP requests, and it will

parse an XML server response The HTTP method (GET/POST) and the destination URL are

then set on the XMLHttpRequest object To be asynchronous:

When you send that HTTP request, you want the page to continue reacting to the user's interaction and deal with the server's response when it eventually arrives

To accomplish this, register a callback function with the XMLHttpRequest and then dispatch the XMLHttpRequest asynchronously

Control then returns to the browser, but the callback function will be called when the server's response arrives.

Page 16: iat352-09-wk11-ajax-web-application0.ppt

16

The Ajax Roundtrip (2)

On web server, the request arrives just like any other HttpServletRequest After parsing the request parameters, the servlet invokes

the necessary application logic, serializes its response into XML, and writes it to the HttpServletResponse

Back on the client side, the callback function registered on the XMLHttpRequest is now invoked to process the XML document returned by the server Finally, the user interface is updated in response to the

data from the server, using JavaScript to manipulate the page's HTML DOM

Page 17: iat352-09-wk11-ajax-web-application0.ppt

17The Ajax Roundtrip

Page 18: iat352-09-wk11-ajax-web-application0.ppt

18

Dispatching an XMLHttpRequest

Creating and dispatching an XMLHttpRequest from the browser Note: the method to

create an XMLHttpRequest differs from browser to browser

Page 19: iat352-09-wk11-ajax-web-application0.ppt

19

Dispatch an Add to Cart XMLHttpRequest

We want to invoke an Ajax interaction whenever the user hits the Add to Cart button for a catalog item The onclick handler function

named addToCart() is responsible for updating the state of the cart through an Ajax call (see Listing 1)

As shown in Listing 3, the first thing that addToCart() needs to do is obtain an instance of XMLHttpRequest by calling the newXMLHttpRequest() function from Listing 2

Next, it registers a callback function to receive the server's response

Page 20: iat352-09-wk11-ajax-web-application0.ppt

20

Servlet request handling Handling an XMLHttpRequest

with a servlet is largely the same as handling a regular HTTP request from a browser A Cart bean is retrieved from the

user's session and its state is updated according to the request parameters

The Cart is then serialized to XML, and that XML is written to the ServletResponse

Note: It's important to set the response's content type to application/xml, otherwise the XMLHttpRequest will not parse the response content into an XML DOM

Page 21: iat352-09-wk11-ajax-web-application0.ppt

21

An example of the XML produced by Cart.toXml() method

Note the generated attribute on the cart element, which is a timestamp produced by: System.currentTimeMillis()

If you take a look at Cart.java in the source code, you'll see that the XML is produced simply by appending strings together

Page 22: iat352-09-wk11-ajax-web-application0.ppt

22

Response handling with JavaScript The readyState property of XMLHttpRequest is a numeric value

that gives the status of the request's lifecycle: 0 (Uninitialized): The object has been created, but not initialized

(the open method has not been called). 1 (Open): The object has been created, but the send method has

not been called. 2 (Sent): The send method has been called. responseText is not

available 3 (Receiving): Some data has been received. responseText is

not available 4 (Loaded): All the data has been received. responseText is

available Each time the readyState changes, the readystatechange

event fires and the handler function attached via the onreadystatechange property is called

Page 23: iat352-09-wk11-ajax-web-application0.ppt

23

Response handling with JavaScript (2)

It is the job of getReadyStateHandler() to return a function that checks whether the XMLHttpRequest has completed, and passes the XML response onto the handler function specified by the caller

Page 24: iat352-09-wk11-ajax-web-application0.ppt

24

About getReadyStateHandler() getReadyStateHandler() is a relatively complex piece of code,

especially if you're not used to reading JavaScript The important thing is that you understand how to use

getReadyStateHandler() in your own code

In Listing 3, you saw getReadyStateHandler() called as follows: handlerFunction = getReadyStateHandler(req, updateCart)

The function returned by getReadyStateHandler() in this case will check if the XMLHttpRequest in the variable req has completed and then call a function named updateCart with the response XML

Page 25: iat352-09-wk11-ajax-web-application0.ppt

25

Extracting the cart data

The function interrogates the shopping cart XML document using DOM calls and updates the Web page (see Listing 1) to reflect the new cart contents

Page 26: iat352-09-wk11-ajax-web-application0.ppt

26

Ajax Design Patterns: HeartBeat How do you know the user still has an

application in the browser and is actively working with it?

Page 27: iat352-09-wk11-ajax-web-application0.ppt

27

Heartbeat sequence

Page 28: iat352-09-wk11-ajax-web-application0.ppt

28

Two Main ways to maintain user records:

In memory The data is not persisted and will be lost once the

user is timed out. In most environments, this will happen if you rely on standard session objects.

Directly in the database Within persistent user records. There's some

extra storage and data maintenance involved, but the benefit is that you always know when the user was last seen

Page 29: iat352-09-wk11-ajax-web-application0.ppt

29

Some relevant issues How much time between Heartbeats? How much delay until a

user is declared inactive? The appropriate figure could vary from subseconds to up to 30

minutes or more depending on the following factors: Application

In some applications, up-to-the-second information is more critical In a multiuser system, for example, users' work may be dictated by

whoever else is present. If you wait 10 minutes to tell Alice that Bob has quit the chess game, she might be annoyed that she wasted the last 10 minutes thinking about her next move

Available resources Ideally, the period should be as short as possible, though you can't

always justify this. For an intranet application, you're likely to use a shorter period in recognition of better resources per user

Page 30: iat352-09-wk11-ajax-web-application0.ppt

30

An Example

Refer to an SFU online book for more details: Ajax Design Patterns: 17.5. Heartbeat