advances & applications in...

37
Advances & Applications in Ajax SEMINAR REPORT MANU T S 12080040 Computer Science and Engineering 2007-2011 School of Engineering CUSAT

Upload: others

Post on 23-Aug-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances & Applications in Ajax

SEMINAR REPORT

MANU T S

12080040 Computer Science and Engineering 2007-2011

School of Engineering CUSAT

Page 2: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

ii

TABLE OF CONTENTS

Chapter No. Title Page

LIST OF TABLES iii

LIST OF FIGURES iv

1. INTRODUCTION……………………………………..……………01

1.1 History……………………………….....................01

2. TRADITIONAL WEB APPLICATIONS………..……………......03

3. AJAX…………………………………..………………………….….07

3.1 The Ajax Web Model………..……………….…....07

3.2 The Ajax Technologies…………………………....08

3.3 Ajax Components and their properties…………….10

4 ANATOMY OF AN AJAX OPERATION…….…………………...12

4.1 steps of Ajax operation……….…………………....12

4.2 other Usage cases of Ajax………..………………...19

5. THE XMLHttpRequest OBJECT…………………....……………....21

Page 3: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

iii

5.1 create an XMLHttpRequest………………….……..21

5.2 send a request to server……………….…….…….....21

5.3 server response……………………………...…….…25

5.4 the ‘onreadystatechange’ event…………….………..26

6 AJAX AND SECURITY………………………………………….…...28

7 CONCLUSION…………………………………………………….…...31

8 REFERENCES………………………………………………….……...32

Page 4: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

iv

LIST OF TABLES

NO. NAME PAGE

1. XMLHttpRequest Methods 22

2. the setRequestHeader 23

3. XMLHttpRequest object attributes 25

4. XMLHttpRequest object properties 26

Page 5: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

v

LIST OF FIGURES

NO. NAME PAGE

1. The Traditional Web Model 03

2. The Traditional Client-Server communication 04

3. The Ajax Web Model 07

4. The Ajax Client-Server communication model 08

5. Anatomy of an ajax Interaction 12

Page 6: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 1

1. INTRODUCTION

Ajax (Asynchronous JavaScript and XML) is a group of interrelated web

development techniques used on the client-side to create interactive web applications. With

Ajax, web applications can retrieve data from the server asynchronously in the background

without interfering with the display and behavior of the existing page. The use of Ajax

techniques has led to an increase in interactive or dynamic interfaces on web pages. Data is

usually retrieved using the XMLHttpRequest object. Despite the name, the use of XML is not

actually required, nor do the requests need to be asynchronous

Like DHTML and LAMP, Ajax is not a technology in itself, but a group of technologies.

Ajax uses a combination of HTML and CSS to mark up and style information. The DOM is

accessed with JavaScript to dynamically display, and to allow the user to interact with the

information presented. JavaScript and the XMLHttpRequest object provide a method for

exchanging data asynchronously between browser and server to avoid full page reloads.

1.1 History

In the 1990s, most web sites were based on complete HTML pages; each user action required

that the page be re-loaded from the server (or a new page loaded). This process is not

efficient, as reflected by the user experience (all page content disappears then reappears, etc.).

Each time a page is reloaded due to a partial change, all of the content must be re-sent instead

of just the changed information. This can place additional load on the server and use

excessive bandwidth.

Asynchronous loading of content first became practical when Java applets were introduced in

the first version of the Java language in 1995. These allow compiled client-side code to load

data asynchronously from the web server after a web page is loaded. In 1996, Internet

Explorer introduced the IFrame element to HTML, which also enabled asynchronous

loading. In 1999, Microsoft created the XMLHTTP ActiveX control in Internet Explorer 5,

which was later adopted by Mozilla, Safari, Opera and other browsers as the native

XMLHttpRequest object. Microsoft has adopted the native XMLHttpRequest model as

of Internet Explorer 7, though the ActiveX version is still supported. The utility of

background HTTP requests to the server and asynchronous web technologies remained fairly

Page 7: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 2

obscure until it started appearing in full scale online applications such as Outlook Web

Access,(2000) Oddpost (2002), and later, notably Google made a wide deployment of Ajax

with Gmail (2004) and Google Maps (2005).

The term "Ajax" was coined in 2005 by Jesse James Garrett. However, a patent application

covering this type of user interface was filed on September 3, 2003, thus predating the term

itself by two years. This application resulted in US Patent #7,523,401 being issued to Greg

Aldridge of Kokomo, IN.

On April 5, 2006 the World Wide Web Consortium (W3C) released the first draft

specification for the object in an attempt to create an official web standard.

Page 8: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 3

2 TRADITIONAL WEB APPLICATIONS

The classic web application model works like this: Most user actions in the interface trigger

an HTTP request back to a web server. The server does some processing — retrieving data,

crunching numbers, talking to various legacy systems — and then returns an HTML page to

the client. It’s a model adapted from the Web’s original use as a hypertext .

The user needs to wait until the response from the server is received successfully and

evaluated. That is user interaction is interrupted and the user has to wait until the response is

processed

Fig 1: the Traditional Web Model

Page 9: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 4

Characteristics of Traditional Web Model

o “Click, wait, and refresh” user interaction

Any communication with the server forces a page refresh

o Synchronous “request/response” communication model

The user has to wait for the response

o Page-driven: Workflow is based on pages

Page-navigation logic is determined by the server

The key characteristics of the model is that the user has to wait until the client-server

communication is over. No user interaction is possible during this interval of time. In slow

networks the user has to wait for a long time causing inconvenience and a major time of the

client user session the user is idle.

Drawbacks of the Traditional Model

o Interruption of user operation

Fig 2: the Traditional client-server communication

Page 10: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 5

Users cannot perform any operation while waiting for a response

o Loss of operational context during refresh

Loss of information on the screen

Loss of scrolled position

o No instant feedback's to user activities

A user has to wait for the next page

o Constrained by HTML

Lack of useful widgets

These drawbacks lead to the development of a new way of client server interaction called

Rich Internet applications (RIA)

Rich Internet Applications (RIAs) are web applications that have many of the

characteristics of desktop applications, typically delivered either by way of a site-specific

browser, via a browser plug-in, or independently sandboxes or virtual machines. Adobe

Flash, Java, and Microsoft Silverlight are currently the three most common platforms .

A Rich Internet application is a Web application designed to deliver the same features and

functions normally associated with desktop applications. RIAs generally split the processing

across the Internet/network divide by locating the user interface and related activity and

capability on the client side, and the data manipulation and operation on the application

server side.

The most commonly used RIA technologies are

• Applet

• Macromedia Flash/Air

• Java WebStart

• DHTML

Page 11: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 6

• DHTML with Hidden Iframe

• Ajax

• Sliverlight (Windows only)

• JavaFX (Java Platform)

Google Suggest and Google Maps are two examples of a new approach to web applications

that we have been calling Ajax.

Page 12: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 7

3. AJAX

AJAX = Asynchronous JavaScript and XML.AJAX is not a new programming language, but

a new way to use existing standards. AJAX is the art of exchanging data with a server, and

update parts of a web page - without reloading the whole page.

3.1 the Ajax Web Model

An Ajax application eliminates the start-stop-start-stop nature of interaction on the Web by

introducing an intermediary — an Ajax engine — between the user and the server. It seems

like adding a layer to the application would make it less responsive, but the opposite is true.

Instead of loading a webpage, at the start of the session, the browser loads an Ajax engine —

written in JavaScript and usually tucked away in a hidden frame. This engine is responsible

for both rendering the interface the user sees and communicating with the server on the user’s

behalf. The 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.

Fig 3: the Ajax Web Model

Page 13: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 8

Every user action that normally would generate an HTTP request takes the form of a

JavaScript call to the Ajax engine instead. Any response to a user action that doesn’t require a

trip back to the server — such as simple data validation, editing data in memory, and even

some navigation — the engine handles on its own. If the engine needs something from the

server in order to respond — if it’s submitting data for processing, loading additional

interface code, or retrieving new data — the engine makes those requests asynchronously,

usually using XML, without stalling a user’s interaction with the application.

3.2 Ajax Technologies

Ajax isn’t a technology. It’s really several technologies, each flourishing in its own right,

coming together in powerful new ways. Ajax incorporates:

standards-based presentation using XHTML and CSS;

dynamic display and interaction using the Document Object Model;

data interchange and manipulation using XML and XSLT;

Fig 4: the Ajax Server-client communication

Page 14: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 9

asynchronous data retrieval using XMLHttpRequest;

and JavaScript binding everything together.

The “asynchronous” part means that the browser isn’t going to wait for data to be returned

from the server, but can handle that data as it’s sent back, when it’s sent back. In other words,

data transfers take place behind the scenes, without making the browser pause and wait for

something to happen. That’s a crucial part of Ajax: You can handle data from the server

when the server sends you that data. You don’t have to put your whole application on hold

until that data arrives. If you had to wait for that data, your application would be

synchronous; and with slow Internet connections, that could be a problem.

The JavaScript part of the term Ajax is also very important because that’s what makes Ajax

happen in the browser. Ajax relies on JavaScript in the browser to connect to the server and

to handle the data that the server sends back. All the Ajax applications you will develop in

this book use JavaScript to connect to the server behind the scenes, uploading and

downloading data. And when your data is downloaded, you can use JavaScript in the browser

to handle that data, displaying it or crunching it as appropriate.

XML has become the lingua franca of the Web, providing a text-based way to send data back

and forth across the Internet. The reason XML has become so popular is that it is indeed text-

based, which means that you can sling XML around the Internet, because the Internet was

designed to handle text-based documents (that is, HTML). For that reason, Ajax applications

are often written to handle data sent back from the server using XML. In other words, when

you contact the server, it’ll send data back to you as an XML document.

Besides JavaScript and XML, Ajax also works with dynamic HTML and Cascading Style

Sheets (CSS). Both of these technologies allow you to update the data displayed in a Web

page, and, because you don’t redraw the entire Web page with Ajax, but just a part of it, you

rely on dynamic HTML and CSS quite a bit; both of them allow you to update specific parts

of a Web page. You’re going to see a lot more on dynamic HTML and CSS in this book

because they allow you to refresh just part of a Web page, something that is central to Ajax-

enabled applications. The part of JavaScript that makes Ajax possible is the

XMLHttpRequest object. This is a special object built into all modern browsers’ version of

Page 15: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 10

JavaScript. As you’re going to see, this is what makes it possible to connect to the server and

handle data sent back from the server behind the scenes. It’s not just JavaScript that makes

Ajax tick, it’s the XMLHttpRequest object inside JavaScript.

Ajax is a collection of technologies, not just a single technology. You use the

XMLHttpRequest object built into JavaScript to connect to the server, and then handle the

XML—or plain text—the server sends back using JavaScript. And you use dynamic HTML

and CSS to display the results in the browser. It’s lucky that all the parts of Ajax applications

came together as they did—JavaScript, the XMLHttpRequest object, dynamic HTML, and

CSS—because all together, they make it possible to make your online applications look like

desktop applications.

3.3 Ajax Components and its Properties

Asynchronous

o the browser isn’t going to wait for data to be returned from the server, but can

handle that data as it is sent back, when it is sent back

o data transfers take place behind the scenes, without making the browser pause

and wait for something to happen

o You don’t have to put your whole application on hold until that data arrives

the JavaScript

o The programming language

o makes Ajax happen in the browser.

o connect to the server behind the scenes, uploading and downloading data

o defines the XMLHttpRequest object

the XML

o provides a text-based way to send data back and forth across the Internet

o when you contact the server, it’ll send data back to you as an XML document.

Page 16: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 11

XSLT

o XSL = Extensible Style sheet Language

o style sheet language for XML documents.

o XSLT = XSL Transformations

DOM

o DOM = Document Object Modeling

o language independent convention for representing and interacting

with objects in HTML,XHTML & XML documents

o The browser keeps an object representation of the documents displayed

XHTML

o XHTML = Extensible Hypertext Markup Language

o XHTML : stricter and cleaner version of HTML.

CSS

o CSS = Cascading Style Sheets

o style sheet language used to describe the presentation semantics (the look and

formatting) of a document written in a markup language

the XMLHttpRequest

o JavaScript object

o a special object built into all modern browser’s version of JavaScript

o Communicates with the browser via the standard Http GET/POST

Page 17: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 12

4.ANATOMY OF AN AJAX INTERACTION

Now let us consider a data validation example of Ajax technology.

The interaction between the client and server is done in 7 steps

4.1 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.The HTML DOM is updated

Fig 5: anatomy of an Ajax Interaction (data validation example)

Page 18: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 13

1. A Client event occurs

• A JavaScript function is called as the result of an event

• Example: validateUserId() JavaScript function is mapped as a event handler to a

onkeyup event on input form field whose id is set to “userid”

<input type="text" size="20"

id="userid" name="id"

onkeyup="validateUserId();">

2. An XMLHttpRequest object is created

var req;

function initRequest()

{

if (window.XMLHttpRequest)

{

req = new XMLHttpRequest();

}

else if (window.ActiveXObject)

{

isIE = true;

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

}

}

function validateUserId()

Page 19: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 14

{

initRequest();

req.onreadystatechange = processRequest;

if (!target) target = document.getElementById("userid");

var url = "validate?id=" + escape(target.value);

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

req.send(null);

}

3. An XMLHttpRequest object is configured with a callback function

var req;

function initRequest()

{

if (window.XMLHttpRequest) {

req = new XMLHttpRequest();

}

else if (window.ActiveXObject)

{

isIE = true;

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

}

function validateUserId()

Page 20: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 15

{

initRequest();

req.onreadystatechange = processRequest; // callback function

if (!target) target = document.getElementById("userid");

var url = "validate?id=" + escape(target.value);

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

req.send(null);

}

4. XMLHttpRequest object makes an async. Request

function initRequest()

{

if (window.XMLHttpRequest)

{

req = new XMLHttpRequest();

}

else if (window.ActiveXObject)

{

isIE = true;

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

}

}

Page 21: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 16

function validateUserId()

{

initRequest();

req.onreadystatechange = processRequest;

if (!target) target = document.getElementById("userid");

var url = "validate?id=" + escape(target.value);

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

req.send(null);

}

5. The ValidateServlet returns an XML document containing the results

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws IOException, ServletException

{

String targetId = request.getParameter("id");

if ((targetId != null) && !accounts.containsKey(targetId.trim()))

{

response.setContentType("text/xml");

response.setHeader("Cache-Control", "no-cache");

response.getWriter().write("<valid>true</valid>");

}

else

Page 22: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 17

{

response.setContentType("text/xml");

response.setHeader("Cache-Control", "no-cache");

response.getWriter().write("<valid>false</valid>");

}

}

6. XMLHttpRequest object calls callback() function and processes the result

The XMLHttpRequest object was configured to call the processRequest()

function when there is a state change to the readyState of the

XMLHttpRequestobject

function processRequest()

{

if (req.readyState == 4)

{

if (req.status == 200)

{

var message = ...;

7. The HTML DOM is updated

JavaScript technology gets a reference to any element in a page using DOM

API

The recommended way to gain a reference to an element is to call

document.getElementById("userIdMessage"), where "userIdMessage" is the

ID attribute of an element appearing in the HTML document

Page 23: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 18

JavaScript technology may now be used to modify the element's attributes;

modify the element's style properties; or add, remove, or modify child

elements

<script type="text/javascript">

function setMessageUsingDOM(message)

{

var userMessageElement =

document.getElementById("userIdMessage");

var messageText;

if (message == "false")

{

userMessageElement.style.color = "red";

messageText = "Invalid User Id";

}

else

{

userMessageElement.style.color = "green";

messageText = "Valid User Id";

}

var messageBody = document.createTextNode(messageText);

// if the messageBody element has been created simple replace it otherwise

// append the new element

Page 24: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 19

if (userMessageElement.childNodes[0])

{

userMessageElement.replaceChild(messageBody,

userMessageElement.childNodes[0]);

}

else

{

userMessageElement.appendChild(messageBody);

}

}

</script>

<body>

<div id="userIdMessage"></div>

</body>

4.2 OTHER Usage cases of Ajax

Real-time server-side input form data validation

o User IDs, serial numbers, postal codes

o Removes the need to have validation logic at both client side for user

responsiveness and at server side for security andother reasons

Auto-completion

o Email address, name, or city name may be auto-completed as the user types

Page 25: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 20

Master detail operation

o Based on a user selection, more detailed information can be fetched and

displayed

Advanced GUI widgets and controls

o Controls such as tree controls, menus, and progress bars may be provided that

do not require page refreshes

Refreshing data

o HTML pages may poll data from a server for up-to-date data such as scores,

stock quotes, weather, or application-specific data

Page 26: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 21

5.THE XMLHttpRequest OBJECT

The keystone of AJAX is the XMLHttpRequest object.

The XMLHttpRequest Object All modern browsers support the XMLHttpRequest object

(IE5 and IE6 uses an ActiveXObject).

The XMLHttpRequest object is used to exchange data with a server behind the scenes. This

means that it is possible to update parts of a web page, without reloading the whole page.

5.1 Create an XMLHttpRequest Object

All modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) have a built-in

XMLHttpRequest object.

Syntax for creating an XMLHttpRequest object: xmlhttp=new XMLHttpRequest();

To handle all modern browsers, including IE5 and IE6, check if the browser supports the

XMLHttpRequest object. If it does, create an XMLHttpRequest object, if not, create an

ActiveXObject:

if(window.XMLHttpRequest)

{//codeforIE7+,Firefox,Chrome, Opera, Safari

xmlhttp=new XMLHttpRequest();

}

else

{// code for IE6, IE5

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

}

5.2 Send a Request To a Server

To send a request to a server, we use the open() and send() methods of the XMLHttpRequest

object:

xmlhttp.open("GET","ajax_info.txt",true);

xmlhttp.send();

Page 27: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 22

Method Description

open(method,url,async) Specifies the type of request, the URL, and if the request should

be handled asynchronously or not.

method: the type of request: GET or POST

url: the location of the file on the server

async: true (asynchronous) or false (synchronous)

send(string) Sends the request off to the server.

string: Only used for POST requests

GET or POST?

GET is simpler and faster than POST, and can be used in most cases.

However, always use POST requests when:

A cached file is not an option (update a file or database on the server)

Sending a large amount of data to the server (POST has no size limitations)

Sending user input (which can contain unknown characters), POST is more robust and

secure than GET

GET Requests

A simple GET request:

xmlhttp.open("GET","demo_get.asp",true);

xmlhttp.send();In the example above, you may get a cached result.

To avoid this, add a unique ID to the URL:

Tab 1. XMLHttpRequest methods

Page 28: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 23

xmlhttp.open("GET","demo_get.asp?t=" + Math.random(),true);

xmlhttp.send();

If you want to send information with the GET method, add the information to the URL:

xmlhttp.open("GET","demo_get2.asp?fname=Henry&lname=Ford",true);

xmlhttp.send();

POST Requests

A simple POST request:

xmlhttp.open("POST","demo_post.asp",true);

xmlhttp.send();

To POST data like an HTML form, add an HTTP header with setRequestHeader(). Specify

the data you want to send in the send() method:

xmlhttp.open("POST","ajax_test.asp",true);

xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");

xmlhttp.send("fname=Henry&lname=Ford");

Method Description

setRequestHeader(header,value) Adds HTTP headers to the request.

header: specifies the header name

value: specifies the header value

The url - A File On a Server

The url parameter of the open() method, is an address to a file on a server:

xmlhttp.open("GET","ajax_test.asp",true);

Tab 2. the setRequestHeader method

Page 29: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 24

The file can be any kind of file, like .txt and .xml, or server scripting files like .asp and .php

(which can perform actions on the server before sending the response back).

Asynchronous - True or False?

AJAX stands for Asynchronous JavaScript and XML, and for the XMLHttpRequest object to

behave as AJAX, the async parameter of the open() method has to be set to true:

xmlhttp.open("GET","ajax_test.asp",true);

Sending asynchronously requests is a huge improvement for web developers. Many of the

tasks performed on the server are very time consuming. Before AJAX, this operation could

cause the application to hang or stop.

With AJAX, the JavaScript does not have to wait for the server response, but can instead:

execute other scripts while waiting for server response

deal with the response when the response ready

When using async=true, specify a function to execute when the response is ready in the

onreadystatechange event:

xmlhttp.onreadystatechange=function()

{

if (xmlhttp.readyState==4 && xmlhttp.status==200)

{

document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

}

}

xmlhttp.open("GET","ajax_info.txt",true);

xmlhttp.send();

To use async=false, change the third parameter in the open() method to false:

Page 30: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 25

xmlhttp.open("GET","ajax_info.txt",false);

Using async=false is not recommended, but for a few small requests this can be ok.

Remember that the JavaScript will NOT continue to execute, until the server response is

ready. If the server is busy or slow, the application will hang or stop.

Note: When you use async=false, do NOT write an onreadystatechange function - just put the

code after the send() statement:

xmlhttp.open("GET","ajax_info.txt",false);

xmlhttp.send();

document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

5.3 Server Response

To get the response from a server, use the responseText or responseXML property of the

XMLHttpRequest object.

Property Description

responseText get the response data as a string

responseXML get the response data as XML data

The responseText Property

If the response from the server is not XML, use the responseText property.The responseText

property returns the response as a string, and you can use it accordingly:

document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

Tab 3. XMLHttpRequest object attributes

Page 31: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 26

The responseXML Property

If the response from the server is XML, and you want to parse it as an XML object, use the

responseXML property:

xmlDoc=xmlhttp.responseXML;

var txt="";

x=xmlDoc.getElementsByTagName("ARTIST");

for (i=0;i<x.length;i++)

{

txt=txt + x[i].childNodes[0].nodeValue + "<br />";

}

document.getElementById("myDiv").innerHTML=txt;

5.4 The onreadystatechange Event

Property Description

onreadystatechange Stores a function (or the name of a function) to be called automatically

each time the readyState property changes

readyState Holds the status of the XMLHttpRequest. Changes from 0 to 4:

0: request not initialized

1: server connection established

2: request received

3: processing request

4: request finished and response is ready

status 200: "OK"

404: Page not found

Tab 4. XMLHttpRequest object properties

Page 32: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 27

When a request to a server is sent, we want to perform some actions based on the

response.The onreadystatechange event is triggered every time the readyState changes.The

readyState property holds the status of the XMLHttpRequest. Three important properties of

the XMLHttpRequest object:

In the onreadystatechange event, we specify what will happen when the server response is

ready to be processed.

When readyState is 4 and status is 200, the response is ready:

xmlhttp.onreadystatechange=function()

{

if (xmlhttp.readyState==4 && xmlhttp.status==200)

{

document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

}

}

Page 33: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 28

6. AJAX and SECURITY

Now that we have reviewed the basics of Ajax, let's discuss its security implications. Ajax

does not inherently introduce new security vulnerabilities in the realm of web applications.

Instead, the applications face the same security issues as classic web applications.

Unfortunately, common Ajax best practices have not been developed, which leaves plenty of

room to get things wrong. This includes proper authentication, authorization, access control

and input validation. Some potential areas of concern involving the use of Ajax include the

following:

Client-side security controls

Some might argue that the dependence on client side programming opens up the possibility of

bringing some already well-known problems back into the forefront. One such possibility

relates to developers improperly implementing security through client-side controls. As we

discussed in the previous section, the use of Ajax requires quite a bit of client-side scripting

code. Web developers are now writing both the server-side and client-side code, so this might

attract developers towards implementing security controls on the client-side. This approach is

horribly insecure because attackers can modify any code running on their client computer

when testing the application for vulnerabilities. Security controls should either be completely

implemented on the server or always re-enforced on the server.

Increased attack surface

A second challenge relates to the difficulty involved in securing the increased attack surface.

Ajax inevitably increases the overall complexity of the system. In the process of adopting

Ajax, developers could code a great number of server-side pages, each page performing some

tiny function (such as looking up a zip code for auto completing a user's city and state fields)

in the overall application. These small pages will each be an additional target for attackers,

and thus an additional point which needs to be secured to ensure a new vulnerability has not

been introduced. This is analogous to the well known security concept of multiple point of

entry into a house: the difficulty involved in securing a house with one door as compared to

securing one with ten doors.

Page 34: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 29

Bridging the gap between users and services

Ajax is a method by which developers bring end users closer to interfaces being exposed by

Service Oriented Architectures The push to create loosely coupled service-based architectures

is a promising idea with many benefits in enterprise environments. As more of these service-

based "endpoints" become developed, and as Ajax introduces the ability to push more

sophisticated processing to the end user, the possibility of moving away from the standard

three-tier model arises.

Typically, many web services within an enterprise (as opposed to on the Internet overall)

were designed for B2B, and therefore designers and developers often did not expect

interaction with actual users. This lack of foresight lead to some bad security assumptions

during design. For example, the initial designers may have assumed that authentication,

authorization and input validation would be performed by other middle tier systems. Once

one allows "outsiders" to directly call these services through the use of Ajax, an unexpected

agent is introduced into the picture. A real-life example of such usage is the consistent pitch

from Microsoft to use hand-in-hand with web services. Developers can now write JavaScript

to create XML input and call the web service right from within the client's browser. In the

past this was achieved through service proxies at the server.

New possibilities for Cross-Site Scripting (XSS)

Another unfortunate truth is that attackers can be more creative (in other words, dangerous)

with the use of Cross Site Scripting (XSS) vulnerabilities. Typically, attackers had to use

XSS holes in a "single-threaded" world, where the attack was being carried out while the

user's browser was in a wait state. This wait state provided some visual/behavioral cues to the

user of a possibly misbehaving application. With the introduction of Ajax, an attacker can

exploit Cross Site Scripting vulnerabilities in a more surreptitious manner. While you check

your mail with an Ajax-enabled application, the malicious code could be sending email to all

your friends without your browser giving you any visual cues at all.

Adequate, specialized security testing must be performed prior to moving the application into

production to address these areas of concern. Even though Ajax applications are web

Page 35: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 30

applications, an organization's existing security testing methodologies may be insufficient

due to the highly interactive nature of these applications

AJAX Security: Server Side

AJAX-based Web applications use the same server side security schemes of

regular Web applications

You specify authentication, authorization, and data protection

requirements in your web.xml file (declarative) or in your program

(programatic)

AJAX-based Web applications are subject to the same security threats as regular

Web applications

Cross-site scripting

Injection flaw

AJAX Security: Client Side

JavaScript code is visible to a user/hacker

o Hacker can use the JavaScript code for inferring server side weaknesses

o Obfustication or compression can be used

JavaScript code is downloaded from the server and executed (“eval”) at the client

o Can compromise the client by mal-intended code

Downloaded JavaScript code is constrained by sand-box security model

o Can be relaxed for signed JavaScript

Page 36: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 31

7. CONCLUSION

The need of interactive web pages leaded to the development of Rich Internet Applications

including Asynchronous JavaScript and XML commonly called as AJAX. Ajax combined the

advantages of several technologies like JavaScript ,XML ,DOM ,XHTML ,CSS ,XSLT etc to

give the web users a desktop like experience on webpages. Ajax using theXMLHttpRequest

object asynchronously communicates with the server in the background which are triggered

by client side events and updates the webpages immediately with interfering the user action.

In comparison to traditional web applications Ajax based applications are more vulnerable to

hackers, viruses etc as more actions are performed on the client side. Slow networks and

browser javascript compatibility take away the beauty of this technology.

Page 37: Advances & Applications in Ajaxdspace.cusat.ac.in/jspui/bitstream/123456789/2358/1/Advances... · • JavaFX (Java Platform) Google Suggest and Google Maps are two examples of a new

Advances and Applications in AJAX

Division Of Computer Science, SOE, CUSAT 32

8.REFERENCES

• http://www.adaptivepath.com/ideas/essays/archives/000385.php

• http://www.symantec.com/connect/articles/ajax-security-basics

• http://en.wikipedia.org/wiki/Ajax_(programming)

• http://www.ibm.com/developerworks/web/library/wa-ajaxintro1.html

• Wiley.Ajax.Bible.Apr.2007