ajax

162
AJAX Atul Kahate [email protected]

Upload: gauravashq

Post on 16-May-2015

583 views

Category:

Education


3 download

DESCRIPTION

Ajax by Atul Kahate Sir at SICSR

TRANSCRIPT

Page 1: Ajax

AJAX

Atul Kahate

[email protected]

Page 2: Ajax

Traditional HTTP Processing

Web Server

Request-

response pairs

(Synchronous

in nature)

AJAX | Atul Kahate 2

Web

Brows

er

in nature)

Page 3: Ajax

AJAX-based Processing

Web Server

JavaScriptAsynchronous

AJAX | Atul Kahate 3

Web

Brows

er

JavaScript

<script>

function

abc() { …}

Update

Asynchronous

operation

Page 4: Ajax

What is AJAX?

� Asynchronous JavaScript and XML

� Allows for asynchronous communication between a browser (client) and server

AJAX | Atul Kahate 4

between a browser (client) and server

� Does not mandate that the end user must wait for processing a request

� Can be used as an alternative to HTML forms in certain situations

Page 5: Ajax

AJAX – Basic FAQ – 1

� Do we not use request/response model in AJAX?

� We do, but the approach is different now. We do not submit a form now, but instead send requests

AJAX | Atul Kahate 5

not submit a form now, but instead send requests using JavaScript

� Why not submit the form? Why AJAX?

� AJAX processing is asynchronous. Client does not wait for server to respond. When server responds, JavaScript does not refresh the whole page.

Page 6: Ajax

AJAX – Basic FAQ – 2

� How does a page get back a response, then?

� When the server sends a response, JavaScript can update a page with new values, change an image, or transfer control to a new page. The user does

AJAX | Atul Kahate 6

or transfer control to a new page. The user does not have to wait while this happens.

� Should we use AJAX for all our requests?

� No. Traditional form filling is still required in many situations. But for immediate and intermediate responses/feedbacks, we should use AJAX.

Page 7: Ajax

AJAX – Basic FAQ – 3

� Where is the XML in AJAX?

� Sometimes the JavaScript can use XML to speak with the server back and forth.

AJAX | Atul Kahate 7

speak with the server back and forth.

Page 8: Ajax

AJAX: Technical Details

Page 9: Ajax

Writing AJAX

� Ability to fetch data from the server without having to refresh a page

� Applications without AJAX� Normal Web applications communicate with the server by referring to a new URL

AJAX | Atul Kahate 9

� Normal Web applications communicate with the server by referring to a new URL

� Example: When a form is submitted, it is processed by a server-side program, which gets invoked

� AJAX applications� Use an object called as XMLHttpRequest object built into the browser, using JavaScript to communicate with the server

� HTML form is not needed to communicate with the server

Page 10: Ajax

The XMLHttpRequest Object

� Alternative for HTML forms

� Used to communicate with the server side code, from inside a browser

AJAX | Atul Kahate 10

� Server side code now returns text or XML data, not the complete HTML Web page

� Programmer has to extract data received from the server via the XMLHttpRequest object, as per the needs

Page 11: Ajax

AJAX Steps

1. Create a request object

2. Tell the request object where to send the request

AJAX | Atul Kahate 11

the request

3. Tell the object what to do when the request is answered

4. Tell the object to make a request

Page 12: Ajax

XMLHttpRequest Object –Technical Details

� In some browsers, this object is native (part of the browser); in some others, it needs to be downloaded (as an ActiveX needs to be downloaded (as an ActiveX control)

� Accordingly, coding changes across browser versions as well

AJAX | Atul Kahate 12

Page 13: Ajax

Ajax Sequence Diagram

AJAX | Atul Kahate 13

Page 14: Ajax

Step 1: Create the XMLHttpRequest Object

Page 15: Ajax

Creating an XMLHttpRequest Object Using JavaScript – 1

� Two main browsers are required to be handled: Internet Explorer and Others� Non-IE code

var XMLHttpRequestObject = false;

AJAX | Atul Kahate 15

var XMLHttpRequestObject = false;

if (window.XMLHttpRequest) { // Non-IE browser

XMLHttpRequestObject = new XMLHttpRequest ();

}

� IE codeelse if (window.ActiveXObject) { // IE browser

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

}

Page 16: Ajax

Creating an XMLHttpRequest Object Using JavaScript – 2

� Now start writing HTML as usual, after checking for the presence of the XMLHttpRequest object

AJAX | Atul Kahate 16

XMLHttpRequest objectif (XMLHttpRequestObject) {

document.write ("<h1>Welcome to AJAX</h1>");

}

Page 17: Ajax

Creating an XMLHttpRequest Object Using JavaScript – 3� Final code (1.html)<html><head><title>AJAX Example</title>

<script language = "javascript">

var XMLHttpRequestObject = false;

if (window.XMLHttpRequest) {XMLHttpRequestObject = new XMLHttpRequest ();

AJAX | Atul Kahate 17

XMLHttpRequestObject = new XMLHttpRequest ();} else if (window.ActiveXObject) {

XMLHttpRequestObject = new ActiveXObject ("Microsoft.XMLHTTP");}

if (XMLHttpRequestObject) {document.write ("<h1>Welcome to AJAX</h1>");

}

</script></head>

<body>

</body>

</html>

Page 18: Ajax

Creating an XMLHttpRequest Object Using JavaScript – 4

� Output

AJAX | Atul Kahate 18

Page 19: Ajax

<div> and <span> HTML Elements

Page 20: Ajax

<div> and <span> - 1

� A <div> HTML container can hold all related elements together and can allow us to style all those elements with one CSS rule

<div id=“menu”>

<a href=“home.html”>home</a>

AJAX | Atul Kahate 20

<a href=“home.html”>home</a>

<a href=“books.html”>writing</a>

<a href=“links.html”>links</a>

<a href=“lib.html”>lib</a>

</div>

� Now we can refer to the div’s id in our CSS, and style all the elements in that div in a uniform manner

Page 21: Ajax

<div> Example

� dummy.html<html>

<head>

<link rel="stylesheet" type="text/css" href="dummy.css" />

</head>

<body>

AJAX | Atul Kahate 21

<body>

<p />

<div id="menu">

<a href="home.html">home</a>

<a href="books.html">writing</a>

<a href="links.html">links</a>

<a href="lib.html">lib</a>

</div>

</body>

</html>

� dummy.css#menu {

font-family: Verdana;

font-color: red;

background-color: silver;

Page 22: Ajax

<div> and <span> - 2

� <span> allows individual element formatting better

<ul>

AJAX | Atul Kahate 22

<ul>

<li><span class=“books”>Books</span></li>

<li><span class=“cd”>CDs</span></li>

<li><span class=“cd”>DVDs</span></li>

</ul>

Page 23: Ajax

<span> Example

� dummy.html modified

� <html>

� <head>

<link rel="stylesheet" type="text/css"

AJAX | Atul Kahate 23

� <link rel="stylesheet" type="text/css" href="dummy.css" />

� </head>

� <body>

� <p />

Page 24: Ajax

Step 2: Tell the object where to send the request (Open the XMLHttpRequest Object)

Page 25: Ajax

Open the XMLHttpRequest Object – 1

� Opening the XMLHttpRequest object prepares it for use to fetch data from the server

AJAX | Atul Kahate 25

the server

� Use the open method

� Mandatory parameters

� Method type (GET, PUT, POST)

� URL

Page 26: Ajax

Open the XMLHttpRequest Object – 2

� Add a form with a Display Message button connected to a JavaScript function named getData

� To prepare for fetching data from the server, pass1. The name of a text file (data.txt) to this function

Also pass the ID of the <div> element where results

AJAX | Atul Kahate 26

2. Also pass the ID of the <div> element where results should be displayed, which is targtDiv

� Create the getData function and add an if statement to check if the XMLHttpRequest object has been created

� Open the XMLHttpRequest object, passing the open Get HTTP method, and the name of the file on the server to be opened

Page 27: Ajax

Open the XMLHttpRequest Object – 3� Final code (2.html)� <!-- 2.html -->

� <html>� <head>� <title>AJAX Example 2</title>

� <script language = "javascript">

� var XMLHttpRequestObject = false;

� if (window.XMLHttpRequest) {

AJAX | Atul Kahate 27

� if (window.XMLHttpRequest) {� XMLHttpRequestObject = new XMLHttpRequest ();� }� else if (window.ActiveXObject) {� XMLHttpRequestObject = new ActiveXObject ("Microsoft.XMLHTTP");� }

� if (XMLHttpRequestObject) {� document.write ("<h2>Welcome to AJAX</h2>");� }

� function getData (divID, dataSource) {� alert ("Hello");� if (XMLHttpRequestObject) {� var obj = document.getElementById (divID);� XMLHttpRequestObject.open ("GET", dataSource);

� obj.innerHTML = "Object opened";� }� }

� </script>� </head>

� <!-- Add a form with a Display Message button connected to a JavaScript function named getData -->

� <body>

� <H1>Fetching data with AJAX</H1>

Page 28: Ajax

Step 3: What to do when the request is answered (Get Ready to Download)

Page 29: Ajax

Downloading Data from Server – 1

� We can download data from the server using the XMLHttpRequest object� Happens ‘behind the scenes’, in an asynchronous manner

� When data comes from the server:

AJAX | Atul Kahate 29

� When data comes from the server:� The readyState property of the HTTPRequestObject changes to one of the following possible values:

� 0 – Uninitialized, 1 – Loading, 2 – Loaded, 3 – Interactive, 4 –Complete

� The status property holds the results of the HTTP download� 200 – OK, 404 – Not found, etc

Page 30: Ajax

Handling Asynchronous Requests

� To handle the response received from asynchronous requests, we need to define a callback function

� For this, associate a function with the XMLHttpRequest object’s onReadyStateChange property like this:

request.onreadystatechange = myFunction, where myFunction is a � request.onreadystatechange = myFunction, where myFunction is a function that would deal with the response;

� Trouble is that with this approach, we cannot pass parameters to the function

� Alternate syntax is to use closures (an linline JavaScript function) like this:

� request.onreadystatechange = function () { myFunction (request) };

� Now, we can pass whatever parameters to the callback function as we like

AJAX | Atul Kahate 30

Page 31: Ajax

Downloading Data from Server – 2� 3.html� <!-- 3.html -->

� <html>� <head>� <title>AJAX Example 3</title>

� <script type = "text/javascript">

� var XMLHttpRequestObject = false;

� if (window.XMLHttpRequest) {

AJAX | Atul Kahate 31

� if (window.XMLHttpRequest) {� XMLHttpRequestObject = new XMLHttpRequest ();� }� else if (window.ActiveXObject) {� XMLHttpRequestObject = new ActiveXObject ("Microsoft.XMLHTTP");� }

� function getData(divID, dataSource) {� if (XMLHttpRequestObject) {� alert ("Hello");� var obj = document.getElementById (divID);� XMLHttpRequestObject.open ("GET", dataSource);

� XMLHttpRequestObject.onreadystatechange = function() {� alert (XMLHttpRequestObject.readyState);� alert (XMLHttpRequestObject.status);� if ((XMLHttpRequestObject.readyState == 4) &&� (XMLHttpRequestObject.status == 200)) {� obj.innerHTML = "Ready to download";� }� }

XMLHttpRequestObject.send (null);

� }� }

� </script>� </head>

� <!-- Add a form with a Display Message button connected to a JavaScript function named getData -->

Page 32: Ajax

XmlHttpRequest Object Properties and Methods

AJAX | Atul Kahate 32

Page 33: Ajax

Properties and Methods – 1

Property/Method Description

readyState Integer indicating the state of the request: 0 = Uninitialized, 1 = Loading, 2 = Response headers received, 3 = Some response body received, 4 = Request complete

onreadystatechange Function to call whenever the readyState changesonreadystatechange Function to call whenever the readyState changes

status HTTP status code returned by the server, such as 200, 404, etc

statusText Full status line returned by the server (eg “OK, No content”)

responseText Full server response as a string

responseXML Server’s response as an XML in the form of a Document object

abort () Cancels a request

AJAX | Atul Kahate 33

Page 34: Ajax

Properties and Methods – 2

Property/Method Description

getAllResponseHeaders ()

Gets all headers in a name/value format

getResponseHeader(header name)

Returs header value corresponding to a specified header name(header name) name

open (method, url, asynch)

Initializes the request for sending to the server

setRequestHeader(name, value)

Adds an HTTP header to the request with a specified value

send (body) Initiates the request to the server

AJAX | Atul Kahate 34

Page 35: Ajax

Step 4: Tell the object to make a request (Download Data with the XMLHttpRequest Object)

Page 36: Ajax

Download Data with the XMLHttpRequest Object – 1

� Using the open method, configure the XMLHttpRequest object to fetch a file named data.txt from the server

� When the button on the screen is clicked, a method named getData is called, to which to which the above file name is passedThe getData function calls the open method on the

AJAX | Atul Kahate 36

� The getData function calls the open method on the XMLHTTPRequest object

� The open method opens the text file on the server using a GET method� Later, we call the send method of the XMLHTTPRequest object to fetch data from this file, by passing a null value to it

� This method fetches data from the text file on to the browser� It is made available inside the responseText property of the XMLHTTPRequest object

� We read that property and assign its value to <div> element

� Note: This page needs to be opened using a Web server URL (http://localhost:8080/ajax/4.html) when Tomcat is running

Page 37: Ajax

Download Data with the XMLHttpRequest Object – 2� <!-- 4.html -->

� <html>� <head>� <title>AJAX Example 3</title>

� <script type = "text/javascript">

� var XMLHttpRequestObject = false;

� if (window.XMLHttpRequest) {� XMLHttpRequestObject = new XMLHttpRequest ();

AJAX | Atul Kahate 37

� XMLHttpRequestObject = new XMLHttpRequest ();� }� else if (window.ActiveXObject) {� XMLHttpRequestObject = new ActiveXObject ("Microsoft.XMLHTTP");� }

� function getData(divID, dataSource) {� if (XMLHttpRequestObject) {� alert ("Hello");� var obj = document.getElementById (divID);� XMLHttpRequestObject.open ("GET", dataSource);

� XMLHttpRequestObject.onreadystatechange = function() {� alert (XMLHttpRequestObject.readyState);� alert (XMLHttpRequestObject.status);� alert (XMLHttpRequestObject.responseText);� if ((XMLHttpRequestObject.readyState == 4) &&� (XMLHttpRequestObject.status == 0)) {� obj.innerHTML = XMLHttpRequestObject.responseText;� }� }� XMLHttpRequestObject.send (null);� }� }

� </script>� </head>

� <!-- Add a form with a Display Message button connected to a JavaScript function named getData -->

Page 38: Ajax

Using Absolute URLs

Page 39: Ajax

Using Absolute URLs – 1

� We can also specify the absolute URL of a file while retrieving data from it from the server side

AJAX | Atul Kahate 39

the server side

Page 40: Ajax

Using Absolute URLs – 2� <!-- 5.html -->

� <html>� <head>� <title>AJAX Example 5</title>

� <script type = "text/javascript">

� var XMLHttpRequestObject = false;

� if (window.XMLHttpRequest) {� XMLHttpRequestObject = new XMLHttpRequest ();

AJAX | Atul Kahate 40

� XMLHttpRequestObject = new XMLHttpRequest ();� }� else if (window.ActiveXObject) {� XMLHttpRequestObject = new ActiveXObject ("Microsoft.XMLHTTP");� }

� function getData(divID, dataSource) {� if (XMLHttpRequestObject) {� alert ("Hello");� var obj = document.getElementById (divID);� XMLHttpRequestObject.open ("GET", dataSource);

� XMLHttpRequestObject.onreadystatechange = function() {� alert (XMLHttpRequestObject.readyState);� alert (XMLHttpRequestObject.status);� alert (XMLHttpRequestObject.responseText);� if ((XMLHttpRequestObject.readyState == 4) &&� (XMLHttpRequestObject.status == 200)) {� obj.innerHTML = XMLHttpRequestObject.responseText;� }� }� XMLHttpRequestObject.send (null);� }� }

� </script>� </head>

� <!-- Add a form with a Display Message button connected to a JavaScript function named getData -->

Page 41: Ajax

Using Server-side Code

Page 42: Ajax

Using Server-side Code – 1

� Instead of reading data from a text file stored on the server, we can invoke a server-side program (e.g. a JSP)

The AJAX-enabled HTML page calls the

AJAX | Atul Kahate 42

� The AJAX-enabled HTML page calls the server-side program on the click of a button

� The server-side program returns text back to the HTML page, which gets displayed on the screen

Page 43: Ajax

Using Server-side Code – 2� <!-- 6.html -->

� <html>� <head>� <title>AJAX Example 6</title>

� <script type = "text/javascript">

� var XMLHttpRequestObject = false;

� if (window.XMLHttpRequest) {� XMLHttpRequestObject = new XMLHttpRequest ();

AJAX | Atul Kahate 43

� XMLHttpRequestObject = new XMLHttpRequest ();� }� else if (window.ActiveXObject) {� XMLHttpRequestObject = new ActiveXObject ("Microsoft.XMLHTTP");� }

� function getData(divID, dataSource) {� if (XMLHttpRequestObject) {� alert ("Hello");� var obj = document.getElementById (divID);� XMLHttpRequestObject.open ("GET", dataSource);

� XMLHttpRequestObject.onreadystatechange = function() {� alert (XMLHttpRequestObject.readyState);� alert (XMLHttpRequestObject.status);� alert (XMLHttpRequestObject.responseText);� if ((XMLHttpRequestObject.readyState == 4) &&� (XMLHttpRequestObject.status == 200)) {� obj.innerHTML = XMLHttpRequestObject.responseText;� }� }� XMLHttpRequestObject.send (null);� }� }

� </script>� </head>

� <!-- Add a form with a Display Message button connected to a JavaScript function named getData -->

Page 44: Ajax

The “X” of AJAX – Using XML

Page 45: Ajax

Using XML – 1

� Create a button with caption Get sandwiches� Write a new function getSandwiches, which gets called when the user clicks on this button

� This function downloads a simple XML file titled sandwiches.xmlfrom the server

The button is also connected to a drop-down list control to

AJAX | Atul Kahate 45

� The button is also connected to a drop-down list control to display sandwich types received from this XML

� Configure the XMLHTTPRequest object to fetch the sandwiches.xml file in the open method

� Add code to extract the contents of this XML file into a variable named xmlDocument, and add code to display a message Got the XML when the XML is succcessfully downloaded

Page 46: Ajax

Using XML – 2� <!-- 7.html -->

� <html>� <head>� <title>AJAX Example 7</title>

� <script type = "text/javascript">

� var XMLHttpRequestObject = false;

� if (window.XMLHttpRequest) {� XMLHttpRequestObject = new XMLHttpRequest ();

AJAX | Atul Kahate 46

� XMLHttpRequestObject = new XMLHttpRequest ();� }� else if (window.ActiveXObject) {� XMLHttpRequestObject = new ActiveXObject ("Microsoft.XMLHTTP");� }

� function getSandwiches () {� if (XMLHttpRequestObject) {� alert ("Hello");

� XMLHttpRequestObject.open ("GET", "sandwiches.xml");

� XMLHttpRequestObject.onreadystatechange = function() {� alert (XMLHttpRequestObject.readyState);� alert (XMLHttpRequestObject.status);� alert (XMLHttpRequestObject.responseXML);� if ((XMLHttpRequestObject.readyState == 4) &&� (XMLHttpRequestObject.status == 200)) {� var xmlDocument = XMLHttpRequestObject.responseXML;� document.write ("Got the XML");� }� }� XMLHttpRequestObject.send (null);� }� }

� </script>� </head>

Page 47: Ajax

Extracting Contents from an XML Document

Page 48: Ajax

Extracting Contents from an XML Document – 1

� Extract an array of XML elements, such as sandwiches by using the getElementsByTagName method, and store that array in a variable named sandwichesAdd the code to pass this sandwiches array

AJAX | Atul Kahate 48

� Add the code to pass this sandwiches array variable to a new function, listSandwiches

� At this point, have the listSandwichesfunction only display a message Got the sandwiches� Later, we will see how to extract the XML contents

Page 49: Ajax

Extracting Contents from an XML Document – 2� <!-- 8.html -->

� <html>� <head>� <title>AJAX Example 8</title>

� <script type = "text/javascript">

� var XMLHttpRequestObject = false;

� if (window.XMLHttpRequest) {� XMLHttpRequestObject = new XMLHttpRequest ();

AJAX | Atul Kahate 49

� XMLHttpRequestObject = new XMLHttpRequest ();� }� else if (window.ActiveXObject) {� XMLHttpRequestObject = new ActiveXObject ("Microsoft.XMLHTTP");� }

� function getSandwiches () {� if (XMLHttpRequestObject) {� alert ("Hello");

� XMLHttpRequestObject.open ("GET", "sandwiches.xml");

� XMLHttpRequestObject.onreadystatechange = function() {� alert (XMLHttpRequestObject.readyState);� alert (XMLHttpRequestObject.status);� alert (XMLHttpRequestObject.responseXML);� if ((XMLHttpRequestObject.readyState == 4) &&� (XMLHttpRequestObject.status == 200)) {� var xmlDocument = XMLHttpRequestObject.responseXML;� var sandwiches = xmlDocument.getElementsByTagName

("sandwich");

� listSandwiches (sandwiches);

� document.write ("Got the XML");� }� }� XMLHttpRequestObject.send (null);� }

Page 50: Ajax

Extracting Data from XML Elements

Page 51: Ajax

Extracting Data from XML Elements – 1

� We can extract data from XML elements by using JavaScript

� In our XML document, we have three

AJAX | Atul Kahate 51

� In our XML document, we have three sandwich elements inside the root element

� We want to extract these elements and display them on the HTML page

Page 52: Ajax

Extracting Data from XML Elements – 2

� The text inside each XML element is considered as a text node� Text node = Data item whose only content is text

� e.g. In<sandwich>cheese</sandwich>, the text

AJAX | Atul Kahate 52

� e.g. In<sandwich>cheese</sandwich>, the text node holds the text cheese

� To extract this text node, we need the syntax of sandwiches[i].firstChild

� The next step is to extract the actual text data from this text node. For this purpose, we need the syntax sandwiches[i].firstChild.data

Page 53: Ajax

Extracting Data from XML Elements – 3

� Modify the listSandwiches function so that it:� stores the drop-down list control in a variable named selectControl

� loops over all <sandwich> elements in the sandwiches array

� Add code to add <option> elements to the select

AJAX | Atul Kahate 53

� Add code to add <option> elements to the select control� The select control’s options property holds an array of <option> elements inside the control, which display items in the control

� To create a new <option> object, use the JavaScript newoperator

� Insert the expression to get the name of the current sandwich type

� We need to pass the text we want to appear in an <option>element to the option constructor method

Page 54: Ajax

Extracting Data from XML Elements – 4� <!-- 9.html -->

� <html>� <head>� <title>AJAX Example 9</title>

� <script type = "text/javascript">

� var XMLHttpRequestObject = false;

� if (window.XMLHttpRequest) {� XMLHttpRequestObject = new XMLHttpRequest ();

AJAX | Atul Kahate 54

� XMLHttpRequestObject = new XMLHttpRequest ();� }� else if (window.ActiveXObject) {� XMLHttpRequestObject = new ActiveXObject ("Microsoft.XMLHTTP");� }

� function getSandwiches () {� if (XMLHttpRequestObject) {� alert ("Hello");

� XMLHttpRequestObject.open ("GET", "sandwiches.xml");

� XMLHttpRequestObject.onreadystatechange = function() {� alert (XMLHttpRequestObject.readyState);� alert (XMLHttpRequestObject.status);� alert (XMLHttpRequestObject.responseXML);� if ((XMLHttpRequestObject.readyState == 4) &&� (XMLHttpRequestObject.status == 200)) {� var xmlDocument = XMLHttpRequestObject.responseXML;� var sandwiches = xmlDocument.getElementsByTagName

("sandwich");

� listSandwiches (sandwiches);� }� }� XMLHttpRequestObject.send (null);� }� }

Page 55: Ajax

Read Data Sent to the Server

Page 56: Ajax

Read Data Sent to the Server – 1

� We can write our scripts on the server to read data passed from the browser to the server

� Write a JSP page to return an XML document

AJAX | Atul Kahate 56

� The HTML page provides two buttons to the user

� On click of the button, call the JSP page to retrieve the XML and display it on the screen

Page 57: Ajax

Read Data Sent to the Server – 2� <!-- 10.html -->

� <html>� <head>� <title>AJAX Example 10</title>

� <script type = "text/javascript">

� var XMLHttpRequestObject = false;

� if (window.XMLHttpRequest) {� XMLHttpRequestObject = new XMLHttpRequest ();

AJAX | Atul Kahate 57

� XMLHttpRequestObject = new XMLHttpRequest ();� }� else if (window.ActiveXObject) {� XMLHttpRequestObject = new ActiveXObject ("Microsoft.XMLHTTP");� }

� function getSandwiches1 () {� if (XMLHttpRequestObject) {

� XMLHttpRequestObject.open ("GET", "ajax10.jsp?type=1");

� XMLHttpRequestObject.onreadystatechange = function() {� if ((XMLHttpRequestObject.readyState == 4) &&� (XMLHttpRequestObject.status == 200)) {� var xmlDocument = XMLHttpRequestObject.responseXML;� var sandwiches = xmlDocument.getElementsByTagName

("sandwich");

� listSandwiches (sandwiches);� }� }� XMLHttpRequestObject.send (null);� }� }

� function getSandwiches2 () {� if (XMLHttpRequestObject) {

� XMLHttpRequestObject.open ("GET", "ajax10.jsp?type=2");

Page 58: Ajax

Read Data Sent to the Server – 3� <%

� String param = request.getParameter ("type");� int type = 0;�

� String [] sandwiches = new String [3];

� if (param != null) {� type = Integer.parseInt (param);� }�

� switch (type) {

AJAX | Atul Kahate 58

� switch (type) {�

� case 1: sandwiches [0] = "hot";� sandwiches [1] = "cold";� sandwiches [2] = "frozen";� break;�

� case 2: sandwiches [0] = "veg";� sandwiches [1] = "jam";� sandwiches [2] = "cheese";� break;� }�

� response.setContentType("text/xml");� out.println ("<?xml version=\"1.0\"?>");� out.println ("<sandwiches>");�

� for (int i=0; i<3; i++) {� out.println ("<sandwich>");� out.println (sandwiches [i]);� out.println ("</sandwich>");� }�

� out.println ("</sandwiches>");� %>

Page 59: Ajax

Using Multiple XMLHttpRequest Objects

Page 60: Ajax

When is this needed?

� If multiple operations (e.g. buttons) use the same XMLHttpRequest object, this can cause confusion

� For example, user may get impatient and click on two buttons – one after the other – quickly; and if both buttons cause the same XMLHttpRequest object to be

AJAX | Atul Kahate 60

buttons – one after the other – quickly; and if both buttons cause the same XMLHttpRequest object to be referred to, we have a problem

� Solution: Use multiple XMLHttpRequest objects

� Ref: D:\tomcat\webapps\examples\ajax\multipleXMLHttpRequest

Page 61: Ajax

11.html� <html>� <head>� <title>Using two XMLHttpRequest Objects</title>�

� <script type = "text/javascript">�

� var menu;�

� var XMLHttpRequestObject1 = false;�

� // alert ("start");�

AJAX | Atul Kahate 61

� if (window.XMLHttpRequest) {� XMLHttpRequestObject1 = new XMLHttpRequest ();� XMLHttpRequestObject1.overrideMimeType ("text/xml");� // alert ("first");� }� else if (window.ActiveXObject) {� XMLHttpRequestObject1 = new ActiveXObject ("Microsoft.XMLHTTP");� }�

� var XMLHttpRequestObject2 = false;�

� if (window.XMLHttpRequest) {� XMLHttpRequestObject2 = new XMLHttpRequest ();� XMLHttpRequestObject2.overrideMimeType ("text/xml");� // alert ("second");� }� else if (window.ActiveXObject) {� XMLHttpRequestObject2 = new ActiveXObject ("Microsoft.XMLHTTP");� }�

� function getMenu1 () {� if (XMLHttpRequestObject1) {� XMLHttpRequestObject1.open ("GET", "menu1.xml");�

� XMLHttpRequestObject1.onreadystatechange = function () {� if (XMLHttpRequestObject1.readyState == 4 && XMLHttpRequestObject1.status == 200) {� var xmlDocument = XMLHttpRequestObject1.responseXML;� menu = xmlDocument.getElementsByTagName ("menuitem");

Page 62: Ajax

menu1.xml

� <?xml version = "1.0"?>

� <menu>

� <menuitem>Main

AJAX | Atul Kahate 62

� <menuitem>Main course</menuitem>

� <menuitem>Fasting</menuitem>

� <menuitem>Salad and Fruits</menuitem>

� </menu>

Page 63: Ajax

menu2.xml

� <?xml version = "1.0"?>

� <menu>

� <menuitem>Tomato</menuitem>

AJAX | Atul Kahate 63

� <menuitem>Tomato</menuitem>

� <menuitem>Cheese</menuitem>

� <menuitem>Cucumber</menuitem>

� </menu>

Page 64: Ajax

Ajax Calculator

Write a simple Ajax application to accept two integers from the user and display their sum on the same screen

NetBeans - AjaxCalculator

Page 65: Ajax

index.html� <html>�

� <head>� <title>Ajax Multiplier</title>� <link rel = "stylesheet" type="text/css" href="calc.css" />� <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">� <script type="text/JavaScript" src="ajax.js"></script> � </head>�

� <body>� <form name = "the_form">� <h1>Ajax Multiplier</h1>

AJAX | Atul Kahate 65

� <h1>Ajax Multiplier</h1>� <br><br>� <h3>Enter integer values below</h3>� <br><br>�

� <table>�

� <tr>� <td>Value 1</td>� <td><input type="text" id = "field_1"></td> � </tr>�

� <tr>� <td>Value 2</td>� <td><input type="text" id = "field_2"></td> � </tr>�

� <tr>� <td align="center">� <input type = "button" id = "submit" value = "Multiply" onclick="multiplyThem();return false;">� </td>� </tr>�

� </table> �

� <br> <br>�

� <table>�

Page 66: Ajax

calc.css� /* � Document : calc� Created on : Nov 19, 2007, 5:20:41 PM� Author : atulk� Description:� Purpose of the stylesheet follows.� */

� /* � TODO customize this sample style� Syntax recommendation http://www.w3.org/TR/REC-CSS2/� */

AJAX | Atul Kahate 66

� */

� h1 { � text-align: center;� color: blue; � font-weight: lighter; � font-family: fantasy;� clip: rect(0px, 0px, 0px, 0px);� letter-spacing: 3px;� }

� td {� font-family: 'Courier New',Courier,monospace;� font-size: 14px;� background-color: #ffffcc;�

� }

� input {� font-family: cursive;� font-size: 14px;�

� }

� table {� border-right-style: groove;� border-left-style: groove;� border-bottom-style: groove;� border-top-style: groove;

Page 67: Ajax

ajax.js� var req;

� function multiplyThem () {� var num_1 = document.the_form.field_1.value;� var num_2 = document.the_form.field_2.value;�

� var url = "MultiplyNumbersServlet?num_1=" + escape (num_1) + "&num_2=" + escape (num_2);�

� if (window.XMLHttpRequest) {� req = new XMLHttpRequest ();� }�

AJAX | Atul Kahate 67

� else if (window.ActiveXObject) {� req = new ActiveXObject ("Microsoft.XMLHTTP");� }�

� req.open ("get", url, true); �

� req.onreadystatechange = callback;� req.send (null);� }

� function callback () {�

� if (req.readyState == 4) {� if (req.status == 200) {� var servlet_response = req.responseText;� // alert (servlet_response);� document.the_form.result.value = servlet_response;� }�

� } �

� }

Page 68: Ajax

MultiplyNumbersServlet.java� /*� * To change this template, choose Tools | Templates� * and open the template in the editor.� */� package com.ajax.servlet;

� import java.io.*;� import java.net.*;

� import javax.servlet.*;� import javax.servlet.http.*;

AJAX | Atul Kahate 68

� /**� *� * @author atulk� */� public class MultiplyNumbersServlet extends HttpServlet {

� protected void doGet(HttpServletRequest request, HttpServletResponse response)� throws ServletException, IOException {� response.setContentType("text/text");� PrintWriter out = response.getWriter();

� String num_1_str = request.getParameter("num_1");� String num_2_str = request.getParameter("num_2");

� System.out.println(num_1_str);� System.out.println(num_2_str);

� try {� int num_1 = Integer.parseInt(num_1_str);� int num_2 = Integer.parseInt(num_2_str);� out.print(num_1 * num_2);� } catch (java.lang.NumberFormatException e) {� e.printStackTrace();� out.print("--- NUMBER ERROR ---");� } � }� }

Page 69: Ajax

Modify Ajax Calculator

AJAX | Atul Kahate 69

Page 70: Ajax

Changes to be done

� Now allow all operations (add, subtract, multiply, divide)

AJAX | Atul Kahate 70

Page 71: Ajax

index-2.html

� Ajax Calculator

Enter integer values below

Value 1 Value 2 Operation (+ - * or /)

Result AJAX | Atul Kahate 71

Page 72: Ajax

ajax-2.js

� var req;

� function computeResult () {� function computeResult () {

� var num_1 = document.the_form.field_1.value;

� var num_2 = document.the_form.field_2.value;

� var operator = document.the_form.field_3.value;

AJAX | Atul Kahate 72

Page 73: Ajax

AllOperationsServlet

� /*

� * To change this template, choose Tools | TemplatesTools | Templates

� * and open the template in the editor.

� */

� package com.ajax.servlet;

� import java.io.*;

� import java.net.*;AJAX | Atul Kahate 73

Page 74: Ajax

AJAX Application

Character Decoder – Allow the user to enter a character and show its ASCII value

(Netbeans – AJAX-Character-Decoder-1)

Page 75: Ajax

index.html� <html>� <head>� <link rel = "stylesheet" type="text/css" href="style.css" />� <script language="JavaScript" src="ajax.js"></script>� <title>Ajax with Java</title>� </head>� <body onload="focusIn ();">� <h1>Ajax Character Decoder</h1>� <h2>Press a key to find its value ...</h2>�

� <table>� <tr>

AJAX | Atul Kahate 75

� <tr>� <td>Enter key Here ->� <input type = "text" id="key" name="key" onkeyup="convertToDecimal ();">� </td>� </tr>� </table>�

� <br />�

� <table>� <tr>� <td colspan = "5" style="border-bottom: solid black 1px;">� Key pressed:� <input type="text" readonly id = "keypressed">� </td>� </tr>�

� <tr>� <td>Decimal</td>� </tr>�

� <tr>� <td>� <input type = "text" readonly id="decimal"> � </td>� </tr>� </table>�

� </body>

Page 76: Ajax

ajax.js� var req;

� function convertToDecimal () {� var key = document.getElementById ("key");� var keypressed = document.getElementById ("keypressed");� keypressed.value = key.value;�

� alert (keypressed.value);�

� var url = "AjaxResponseServlet?key=" + escape (key.value);

� if (window.XMLHttpRequest) {

AJAX | Atul Kahate 76

� if (window.XMLHttpRequest) {� req = new XMLHttpRequest ();� }� else if (window.ActiveXObject) {� req = new ActiveXObject ("Microsoft.XMLHTTP");� }�

� req.open ("get", url, true);�

� req.onreadystatechange = callback;� req.send (null);� }

� function callback () {

� alert ("readyState = " + req.readyState);� alert ("status = " + req.status);

� if (req.readyState == 4) {� if (req.status == 200) {� var decimal = document.getElementById ('decimal');� decimal.value = req.responseText;� }� }� clear ();� }

� function clear () {� var key = document.getElementById ("key");

Page 77: Ajax

style.css� body {� font-family: Arial, Helvetica, sans-serif;� font-size: small;� text-align: center;� background: #cbdada;� }

� #keypressed {� width: 30;� border: none;� }

AJAX | Atul Kahate 77

� #key {� width: 20px;� padding: 0;� margin: 0;� border: none;� text-align: left;� }

� h1, h2 {� font-size: 120%;� text-align: center;� }

� h2 {� font-size: 110%;� }

� table, input {� margin-left: auto;� margin-right: auto;� padding: 0px 10px;� text-align: center;� color: black;� background: #a0f6f5;� border: solid black 1px;� }

� td {

Page 78: Ajax

AjaxResponseServlet.java� /*� * AjaxResponseServlet.java� *� * Created on September 21, 2007, 2:58 PM� */

� package com.ajax.servlet;

� import java.io.*;� import java.net.*;

� import javax.servlet.*;

AJAX | Atul Kahate 78

� import javax.servlet.*;� import javax.servlet.http.*;

� /**� *� * @author AtulK� * @version� */� public class AjaxResponseServlet extends HttpServlet {�

� public static final long serialVersionUID = 1L;� // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">� /** Handles the HTTP <code>GET</code> method.� * @param request servlet request� * @param response servlet response� */� protected void doGet(HttpServletRequest request, HttpServletResponse response)� throws ServletException, IOException {�

� System.out.println("Inside servlet");�

� String key = request.getParameter("key");�

� System.out.println("Key = " + key);�

� if (key != null) {� // Extract first character from key as int, and convert it into a string� int keychar = key.charAt(0);

Page 79: Ajax

web.xml� <?xml version="1.0" encoding="UTF-8"?>� <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">� <servlet>� <servlet-name>AjaxResponseServlet</servlet-name>� <servlet-class>com.ajax.servlet.AjaxResponseServlet</servlet-class>� </servlet>� <servlet-mapping>� <servlet-name>AjaxResponseServlet</servlet-name>

<url-pattern>/AjaxResponseServlet</url-pattern>

AJAX | Atul Kahate 79

� <url-pattern>/AjaxResponseServlet</url-pattern>� </servlet-mapping>� <session-config>� <session-timeout>� 30� </session-timeout>� </session-config>� <welcome-file-list>� <welcome-file>� index.jsp� </welcome-file>� </welcome-file-list>� </web-app>

Page 80: Ajax

Exercise

� Modify the above example to allow the user to type. As soon as the user types a character, get all the matching entries

AJAX | Atul Kahate 80

a character, get all the matching entries starting with that character and display back to the user

� NetBeans: Ajax-Character-Decoder-2

Page 81: Ajax

index.html� <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

� <html>� <head>� <link rel = "stylesheet" type="text/css" href="style.css" />� <script type="text/JavaScript" src="ajax.js"></script>� <title>Ajax with Java</title>� </head>� <body onload="focusIn ();">� <h1>Get Matching Values from the Database</h1>� <p><p>� <h2>Press a key to get matching values ...</h2>

AJAX | Atul Kahate 81

� <h2>Press a key to get matching values ...</h2>�

� <table>� <tr>� <td>Enter key Here ->� <input type = "text" id="key" name="key" onkeyup="getMatchingValues ();">� </td>� </tr>� </table>�

� <br />�

� <table>� <tr>� <td>� Key pressed:� <input type="text" readonly id = "keypressed">� </td>� </tr>�

� <tr>� <td>Matching values</td>� </tr>�

� <tr>� <td> � <input type = "text" id = "decimal" readonly value = ""> � </td>� </tr>

Page 82: Ajax

style.css� body {� font-family: Arial, Helvetica, sans-serif;� font-size: small;� text-align: center;� background: #cbdada;� }

� h1, h2 {� font-size: 120%;� text-align: center;� }

AJAX | Atul Kahate 82

� h2 {� font-size: 110%;� }

� table, input {� margin-left: auto;� margin-right: auto;� padding: 0px 10px;� text-align: center;� color: black;� background: #a0f6f5;� border: solid black 1px;� }

� td {� margin: 10px;� padding: 0px 5px;� border: none;� }

� input {� width: 300;� border: none;� border-top: solid #999999 1px;� font-size: 80%;� color: #555555;� }

Page 83: Ajax

ajax.js� var req;

� function getMatchingValues () {�

� // decimal.clear ();� var key = null;� key = document.getElementById ("key");� var keypressed = document.getElementById ("keypressed");� keypressed.value = key.value;�

� // alert (keypressed.value);�

AJAX | Atul Kahate 83

� var url = "AjaxResponseServlet?key=" + escape (key.value);

� if (window.XMLHttpRequest) {� req = new XMLHttpRequest ();� }� else if (window.ActiveXObject) {� req = new ActiveXObject ("Microsoft.XMLHTTP");� }�

� req.open ("get", url, true);�

� req.onreadystatechange = callback;� req.send (null);� }

� function callback () {

� // alert ("readyState = " + req.readyState);� // alert ("status = " + req.status);

� if (req.readyState == 4) {� if (req.status == 200) {� var decimal = document.getElementById ('decimal');� // alert (req.responseText);� decimal.value = req.responseText;� }� }� clear ();

Page 84: Ajax

AjaxResponseServlet.java� /*� * AjaxResponseServlet.java� *� * Created on September 21, 2007, 2:58 PM� */� package com.ajax.servlet;

� import java.io.*;� import java.net.*;

� import javax.servlet.*;� import javax.servlet.http.*;

AJAX | Atul Kahate 84

� import javax.servlet.http.*;

� import java.sql.*;� import java.util.*;

� /**� *� * @author AtulK� * @version� */� public class AjaxResponseServlet extends HttpServlet {

� protected void doGet(HttpServletRequest request, HttpServletResponse response)� throws ServletException, IOException {

� String key = request.getParameter("key");

� System.out.println("Key = " + key);

� List userIds = new ArrayList ();

� if (!key.equals("")) {

� try {

� Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/users");� ResultSet rs = null;

� PreparedStatement ps = con.prepareStatement("SELECT user_id FROM user_table WHERE user_id like ? ");

Page 85: Ajax

Account Balance Example

NetBeans Ajax-Misc

AJAX | Atul Kahate 85

Page 86: Ajax

Requirements

� User types an account number. Show corresponding account balance. Also show one of the following messages:show one of the following messages:

� Success

� Account number is invalid

� Error in processing

AJAX | Atul Kahate 86

Page 87: Ajax

getAccountDetails.html

� Account Details

Enter acocunt details

Account Number Account Balance

Status AJAX | Atul Kahate 87

Page 88: Ajax

account.js

� var req;

� function getAccountDetails () {� function getAccountDetails () {

� var accountNumber = document.the_form.field_1.value;

� // alert ("inside JS");

� var url = AJAX | Atul Kahate 88

Page 89: Ajax

getAccountDetails.jsp

� <%@ page import="java.util.*" %>

� <%@ page import="com.ajax.serverside.Account" import="com.ajax.serverside.Account" %>

� <%

� String accountNumber = request.getParameter ("accountNumber");AJAX | Atul Kahate 89

Page 90: Ajax

Account.java

� /*

� * To change this template, choose Tools | TemplatesTools | Templates

� * and open the template in the editor.

� */

� package com.ajax.serverside;

� /**AJAX | Atul Kahate 90

Page 91: Ajax

Case Study – Building an AJAX Application

Page 92: Ajax

Requirements

� We have a book shop, where we want to constantly view the amount of profit we have made

For this purpose, the server-side code sends

AJAX | Atul Kahate 92

� For this purpose, the server-side code sends us the latest number of copies sold, as on date

� We multiply that with the profit per copy (sale price less purchase price), and compute the total profit made

Page 93: Ajax

Traditional Application Example

Web form that submits the

JSP returns

AJAX | Atul Kahate 93

submits the request to a JSP page

returns the latest number of copies sold

Page 94: Ajax

Execution Steps – 1User clicks here

AJAX | Atul Kahate 94

Page 95: Ajax

Execution Steps – 2

Reload!

AJAX | Atul Kahate 95

Server sends a response now

Reload!

Page 96: Ajax

Code for the AJAX Version

� Several basic concepts are needed to understand this, and hence, we shall study it after the theoretical and

AJAX | Atul Kahate 96

study it after the theoretical and conceptual overview

� Come back to the next slide later, once the basic concepts are finished

Page 97: Ajax

Application Design

� Our code would have the following JavaScript functions:� getBooksSold ()

AJAX | Atul Kahate 97

� Would create a new object to talk to the server

� updatePage ()� Would ask the server for the latest book sales figures

� createRequest ()� Set the number of books sold and profit made

Page 98: Ajax

The HTML Part (d:\tomcat\webapps\examples\AJAX\books.html)

<html>

<head>

<title>Sales Report</title>

<link rel="stylesheet" type="text/css" href="books.css" />

</head>

<body>

<h1>Sales Report for our Books</h1>

<div id="Books">

AJAX | Atul Kahate 98

<div id="Books">

<table>

<tr><th>Books Sold</th>

<td><span id="books-sold">555</span></td></tr>

<tr><th>Sell Price</th>

<td>Rs. <span id="price">300</span></td></tr>

<tr><th>Buying Cost</th>

<td>Rs. <span id="cost">250</span></td></tr>

</table>

<h2>Profit Made: Rs. <span id="cash">27750</span></h2>

<form method="GET" action="getUpdatedBookSales.jsp">

<input value="Show me the latest profit" type="button" />

</form>

</div>

</body>

</html>

Page 99: Ajax

Add JavaScript Now

AJAX | Atul Kahate 99

On click of the button, call a JavaScript function getBooksSold ()

Page 100: Ajax

The getBooksSold () Function

� Create a new request by calling the createRequest () function

� Specify the URL to receive the updates from

AJAX | Atul Kahate 100

� Specify the URL to receive the updates from

� Set up the request object to make a connection

� Request an updated number of books sold

Page 101: Ajax

JavaScript Code Outline

<script language=“javascript” type=“text/javascript”>

AJAX | Atul Kahate 101

function createRequest ()// JavaScript code

function getBooksSold ()createRequest ();

</script>

Page 102: Ajax

createRequest () Function

� This function would simply try to create an instance of the XMLHttpRequest object, as per the browser type

AJAX | Atul Kahate 102

function createRequest () {

if (window.XMLHttpRequest) {

XMLHttpRequestObject = new XMLHttpRequest ();

}

else

if (window.ActiveXObject) {

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

}

}

Page 103: Ajax

Now Modify getBooksSold ()

function getBooksSold () {

createRequest ();

var url = "getUpdatedBookSales.jsp";

AJAX | Atul Kahate 103

XMLHttpRequestObject.open ("GET", url);

� This would call getUpdatedBookSales.jsp

� We want to process the response sent by this JSP now

Page 104: Ajax

Now, Process the Results

function getBooksSold () {

createRequest ();

var url = "getUpdatedBookSales.jsp";

XMLHttpRequestObject.open ("GET", url);

AJAX | Atul Kahate 104

XMLHttpRequestObject.onreadystatechange = updatePage;XMLHttpRequestObject.send (null);

� How does this work?

Page 105: Ajax

updatePage ( ) Needs to do this

Updated number of books sold

AJAX | Atul Kahate 105

JavaScript

Update these now

Page 106: Ajax

When to call updatePage ()?

� When this function receives a response from JSP, it needs to update the values on the screen, making this asynchronous

AJAX | Atul Kahate 106

asynchronous

� Hence, we have:XMLHttpRequestObject.onreadystatechange = updatePage;

� Call updatePage () when a response is received

Page 107: Ajax

updatePage () Function – 1

� First read the response sent by the JSP page

AJAX | Atul Kahate 107

function updatePage () {

var newTotal = XMLHttpRequestObject.responseText;

� This would read the updated values of books sold to date from the server-side into a JavaScript variable called as newTotal

Page 108: Ajax

updatePage () Function – 2

function updatePage () {var newTotal = XMLHttpRequestObject.responseText;

var booksSoldElement = document.getElementById ("books-sold");

AJAX | Atul Kahate 108

("books-sold");

var cashElement = document.getElementById ("cash");

� Now, read the current values of the HTML elements books-sold and cash into two JavaScript variables

� We want to update these on the screen

Page 109: Ajax

updatePage () Function – 3

function updatePage () {

var newTotal = XMLHttpRequestObject.responseText;

var booksSoldElement = document.getElementById

AJAX | Atul Kahate 109

var booksSoldElement = document.getElementById ("books-sold");

var cashElement = document.getElementById ("cash");

replaceText (booksSoldElement, newTotal);

� This is our own function, which will replace the current HTML element’s value with the updated one, on the screen

Page 110: Ajax

What should the JSP do?

� Normally, the JSP would return a full HTML

� Now, it has to return a single number:

AJAX | Atul Kahate 110

� Now, it has to return a single number: number of books sold at this moment

� Hence, the JSP just has:

out.print (300);

Page 111: Ajax

Want to see how it really works?

� Change the JSP to introduce delays

<% for (int i=1; i<40000; i++) { for (int j=1; j<40000; j++); } for (int i=1; i<40000; i++); for (int i=1;

AJAX | Atul Kahate 111

j++); } for (int i=1; i<40000; i++); for (int i=1; i<40000; i++);

out.print ("300");

%>

� Now rerun the application

Page 112: Ajax

Modify the example to expect an XML from the JSP

D:\tomcat\webapps\ajax\books-xml-version

AJAX | Atul Kahate 112

Page 113: Ajax

Initial Screen

AJAX | Atul Kahate 113

Page 114: Ajax

Requirements – 1

� When the user clicks on the button, the browser should send a request to the JSP as beforeJSP as before

� The JSP would now send an XML document, containing the following:<?xml version="1.0"?>

<total-sale>

<complete-reference-books>20</complete-reference-books>

<professional-books>35</professional-books>

<head-first-books>15</head-first-books>

</total-sale>

AJAX | Atul Kahate 114

Page 115: Ajax

Requirements – 2 - Result

AJAX | Atul Kahate 115

Page 116: Ajax

books.html

� <html>

� <head>

� <title>Sales Report</title>� <title>Sales Report</title>

� <link rel="stylesheet" type="text/css" href="books.css" />

� <script language = "javascript" type = "text/javascript">

AJAX | Atul Kahate 116

Page 117: Ajax

getUpdatedBookSales.jsp

� <%

� response.setContentType("text/xml")� response.setContentType("text/xml");

� out.println ("<?xml version=\"1.0\"?>");

� out.println ("<total-sell>");

AJAX | Atul Kahate 117

Page 118: Ajax

books.css

� body {

� font-family: Verdana;

� }� }

� h1 {

� background-color: silver;

� }

h2 {

AJAX | Atul Kahate 118

Page 119: Ajax

User ID – Case Study

NetBeans – Ajax-Misc

AJAX | Atul Kahate 119

Page 120: Ajax

Requirements

� Accept a user ID from the user for new ID creation

� If it is free, accept user name and allow � If it is free, accept user name and allow user to create/cancel a new user

� If it is already taken, show an error message and allow to choose another ID

AJAX | Atul Kahate 120

Page 121: Ajax

checkUserID.html

� User ID Details

Enter user ID details

User ID Status

AJAX | Atul Kahate 121

Page 122: Ajax

user.css

� /*

� Document : user

� Created on : Jun 9, 2008, 2:30:51 � Created on : Jun 9, 2008, 2:30:51 PM

� Author : atulk

� Description:

� Purpose of the stylesheet follows.

� */AJAX | Atul Kahate 122

Page 123: Ajax

user.js

� var req;

� function getUserID () {� function getUserID () {

� var userID = document.the_form.field_1.value;

� // alert ("inside JS");

� var url = "getUserID.jsp?userID=" + AJAX | Atul Kahate 123

Page 124: Ajax

getUserID.jsp

� <%@ page import="java.util.*" %>

� <%@ page import="java.sql.*" %>

� <%@ page � <%@ page import="com.ajax.serverside.User" %>

� <%

� String userID = request.getParameter("userID");

� ResultSet rs = null;AJAX | Atul Kahate 124

Page 125: Ajax

createNewUser.jsp

� <%@ page import="java.util.*" %>

� <%@ page import="java.sql.*" %>

� <%@ page � <%@ page import="com.ajax.serverside.User" %>

� <%

� String userID = request.getParameter("userID");

� String userName = AJAX | Atul Kahate 125

Page 126: Ajax

JSON (JavaScript Object Notation)

AJAX | Atul Kahate 126

Page 127: Ajax

What is JSON?

� Alternative to XML when we do not need advanced capabilities of XML, such as validations, formatting using XSLT, as validations, formatting using XSLT, etc

� When we use XML as a simple means of transmitting data between two points, we can use JSON instead of XML

AJAX | Atul Kahate 127

Page 128: Ajax

JSON Advantages

� JSON is lightweight

� Data represented in JSON is quite concise

� Like XML, JSON is also human-readable (but not to the level of XML)the level of XML)

� Performance when parsing JSON is quite good

� JSON can be recognized and parsed by JavaScript alone unlike XML, where we need special APIs to deal with XML

AJAX | Atul Kahate 128

Page 129: Ajax

JSON Technical Details

� JSON is a small subset of the JavaScript language, aimed at representing structured data. This means that we need to follow certain JavaScript syntax, which enables us to deal with the following constructs:

� Objects – These are unordered sets of name/value pairs. They start and end with the { and } symbols, respectively.

� Arrays – These are ordered collections of values. They start and end with the [ and ] symbols, respectively.

� Values – These are strings, numbers, Boolean values, nested objects, arrays, etc.

AJAX | Atul Kahate 129

Page 130: Ajax

XML Versus JSON

<?xml version=”1.0”?>

<books>

<book>

<title>Computer Networks</title>

<author>Andrew Tanenbaum</author>

</book>

{ “books”: [

{ “book”: { “title”: “Computer Networks”,

“author”: “Andrew Tanenbaum”}},

{ “book”: { “title”: “TCP/IP”,

“author”: “Douglas Comer”}},

{ “book”: { “title”: “C: The Complete Reference”,

AJAX | Atul Kahate 130

<book>

<title>TCP/IP</title>

<author>Douglas Comer</author>

</book>

<book>

<title>C: The Complete Reference</title>

<author>Herbert Schildt</author>

</book>

</books>

“author”: “Andrew Tanenbaum”}}

]

}

XML JSON

Page 131: Ajax

Creating JSON on the Server (in Java)

� String myString = new JSONObject().put (“title”, “TCP/IP”).toString ();

� This creates a Java String named myString, containing the value {“title”: “TCP/IP”}.

� We can add it to our JSON text.

� Later, we can parse this on the client-side, as shown next.

AJAX | Atul Kahate 131

Page 132: Ajax

Parsing JSON in JavaScript

� How do we parse a JSON document? It is very simple, and can be accomplished by one line of JavaScript code:

� var result = eval (‘(‘ + jsonText + ‘)’);

� This statement parses the JSON text and produces a JavaScript-� This statement parses the JSON text and produces a JavaScript-compatible object out of it.

� Once we have the parsed JSON document available to us as a JavaScript variable, the next steps are very easy:

� var thirdBookTitle = result.books[3].book.title;

� This would read the title of the third book of our JSON text and store it inside a JavaScript variable.

AJAX | Atul Kahate 132

Page 133: Ajax

JSON Drawbacks

� While being less verbose than XML makes JSON faster, it can also become a drawback if we actually expect the content representation to be verbose

� There is no concept of namespaces in JSON, making the possibility of mixing contents from different sources seamlessly possibility of mixing contents from different sources seamlessly more difficult as compared to XML

� What are element-equivalent portions and what are attribute-equivalent portions in JSON is not very clear, in contrast to XML

� Creation and validation of JSON documents is more difficult as compared to XML

AJAX | Atul Kahate 133

Page 134: Ajax

JSON Example (Same Books Example now in JSON)

D:\tomcat\webapps\ajax\books-json-version

AJAX | Atul Kahate 134

Page 135: Ajax

books.html

� <html>

� <head>

� <title>Sales Report</title>� <title>Sales Report</title>

� <link rel="stylesheet" type="text/css" href="books.css" />

� <script language = "javascript" type = "text/javascript">

AJAX | Atul Kahate 135

Page 136: Ajax

getUpdatedBookSales.jsp

� <%

� out.println ("{\"totalSale\": [");� out.println ("{\"totalSale\": [");

� out.println ("{");

� out.println ("\"completeReferenceBooks\": 20,");

� out.println ("\"professionalBooks\": 35,");

AJAX | Atul Kahate 136

Page 137: Ajax

books.css

� body {

� font-family: Verdana;

� }� }

� h1 {

� background-color: silver;

� }

h2 {

AJAX | Atul Kahate 137

Page 138: Ajax

Second Case Study – Pizza Delivery

Page 139: Ajax

Requirements

User would type the phone number here. Once

AJAX | Atul Kahate 139

here. Once finished, the customer’s address details should be shown automatically.

Page 140: Ajax

Processing Steps

1. Customer enters phone number.

2. A JavaScript function gets called.

3. This JavaScript function sends the customer’s phone number to the server and asks for the

AJAX | Atul Kahate 140

phone number to the server and asks for the customer’s address.

4. While the server is looking up for the customer’s address, the customer can enter order details.

5. The browser calls a JavaScript function that updates the Web page in the browser with the customer’s address.

Page 141: Ajax

HTML for the Basic Page

� pizzaDelivery.html<html>

<head>

AJAX | Atul Kahate 141

<head>

<title>Pizza Delivery Page</title>

<link rel="stylesheet" type="text/css" href="pizzaDelivery.css" />

</head>

<body>

<form method="POST" action="placeOrder.jsp">

<p>Enter your phone number:

Page 142: Ajax

CSS for the Basic Page

� pizzaDelivery.cssbody {

font-family: Verdana;

background-color: black;

AJAX | Atul Kahate 142

background-color: black;

}

p {

font-size: large;

color: red;

}

textarea {

Page 143: Ajax

Event Handling

� We need to capture an event to know when the customer provides a phone number� onChange – Gets called when the value in a form field changes (e.g. typing a new value or clearing

AJAX | Atul Kahate 143

field changes (e.g. typing a new value or clearing an existing one)

� onFocus – Gets called when the user enters a field in the form

� onBlur – Gets called when the user leaves a field

� We would use onChange

� Modifying the form now …

Page 144: Ajax

Modified HTML Page

� <html>

� <head>

<title>Pizza Delivery Page</title>

AJAX | Atul Kahate 144

� <title>Pizza Delivery Page</title>

� <link rel="stylesheet" type="text/css" href="pizzaDelivery.css" />

� </head>

� <body onLoad="document.forms[0].reset();">

� <form method="POST"

Page 145: Ajax

Writing the getCustomerInfo () Function – 1

� We need to obtain the value of the phone number entered by the user

AJAX | Atul Kahate 145

function getCustomerInfo () {

var phone = document.getElementById (“phone”).value;

Page 146: Ajax

Writing the getCustomerInfo () Function – 2

� Next, we want to request for the customer’s address

1. Create a request object.

AJAX | Atul Kahate 146

1. Create a request object.

2. Send the request, containing the phone number to the server.

3. Write the server-side code to process this request.

Page 147: Ajax

Writing the getCustomerInfo () Function – 3

function getCustomerInfo ( ) {

var phone = document.getElementById (“phone”).value;

var url = “lookupCustomer.jsp?phone=“ + escape

AJAX | Atul Kahate 147

var url = “lookupCustomer.jsp?phone=“ + escape (phone);

request.open (“GET”, url, true);

request.onreadystatechange = updatePage;

request.send (null);

}

Page 148: Ajax

Full HTML (C:\tomcat\webapps\examples\AJAX\pizza)

� <html>

� <head>

<title>Pizza Delivery Page</title>

AJAX | Atul Kahate 148

� <title>Pizza Delivery Page</title>

� <link rel="stylesheet" type="text/css" href="pizzaDelivery.css" />

� <script language = "javascript" type = "text/javascript">

� var XMLHttpRequestObject = null;

Page 149: Ajax

JSP Page

� <%

� for (int i=1; i<30000; i++)

for (int j=1; j<30000; j++)

AJAX | Atul Kahate 149

� for (int j=1; j<30000; j++)

� for (int k=1; k<5; k++);

� out.print ("Pune");

� %>

Page 150: Ajax

Exercise

� Modify the JSP page to read the address from a database

AJAX | Atul Kahate 150

Page 151: Ajax

Modified JSP

� <%@page import="java.sql.*" %>

� <%@page import="java.util.*" %>

<%

AJAX | Atul Kahate 151

� <%

� // Open Database Connection

� Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");

� // Open a connection to the database

� Connection con = DriverManager.getConnection("jdbc:odbc:cust

Page 152: Ajax

Another Case Study – Coffee Maker

Page 153: Ajax

User Interface

Place your coffee order here:

Coffee Maker

#1

Idle

Coffee Maker

#2

Idle

AJAX | Atul Kahate 153

-ame: ________________________

Size

Small O Medium O Large O

Beverage

Mocha O Black Coffee O Filter Coffee O

Order Coffee

Page 154: Ajax

Requirements

� Initially, both Coffee Maker #1 and #2 would be idle

� Whenever anyone submits an order for

AJAX | Atul Kahate 154

� Whenever anyone submits an order for coffee, Maker#1 comes into action, and needs some time to make coffee

� During this time if another order comes, it needs to be processed by Maker #2

Page 155: Ajax

Application Structure

� Coffee maker HTML� Take orders, report status of the two makers

� JavaScript codeCreate a request object, a function to send order

AJAX | Atul Kahate 155

� Create a request object, a function to send order to the coffee-making script, serve a drink when ready, Event handlers to connect the form buttons to JavaScript functions

� Server-side code� Coffee-making script when an order is placed, should be able to handle two requests at a time

Page 156: Ajax

Application Flow – 1

� The Web page should display the status of both coffee makers (Idle initially)

Coffee Coffee

AJAX | Atul Kahate 156

Place your coffee order here:-ame: ________________________

Size

Small O Medium O Large O

Beverage

Mocha O Black Coffee O Filter Coffee O

Order Coffee

Coffee

Maker #1

Idle

Coffee

Maker #2

Idle

Page 157: Ajax

Application Flow – 2

Place your coffee order here:

Coffee

Maker #1

Idle

Coffee

Maker #2

Idle

The JavaScript should be

<script>

Var XmlHttp …

<!– Server side code for coffee making -->

<% if … %>

AJAX | Atul Kahate 157

Place your coffee order here:-ame: ________________________

Size

Small O Medium O Large O

Beverage

Mocha O Black Coffee O Filter Coffee O

Order Coffee

The JavaScript should be able to send requests to brew coffee to the coffee maker script on the server and handle response received from the server. It also needs to update the status of the coffee maker, and let the users know when the coffee is

ready.

Page 158: Ajax

Application Flow – 3

Place your coffee order here:

Coffee

Maker #1

Idle

Coffee

Maker #2

Idle

The server-side code is quite

<script>

Var XmlHttp …

<!– Server side code for coffee making -->

<% if … %>

AJAX | Atul Kahate 158

Place your coffee order here:-ame: ________________________

Size

Small O Medium O Large O

Beverage

Mocha O Black Coffee O Filter Coffee O

Order Coffee

The server-side code is quite simple. It takes a request to brew coffee along with the cup size, coffee type, and

name of the person. Once the coffee is ready, it sends back the response along with the name of the person who placed the order.

Page 159: Ajax

Sample Flow – 1

Place your coffee order here:

Coffee

Maker #1

Idle

Coffee

Maker #2

Idle

Sachin has placed an order for

<script>

Var XmlHttp …

<!– Server side code for coffee making -->

<% if … %>

AJAX | Atul Kahate 159

Place your coffee order here:-ame: __Sachin_____________________

Size

Small Medium O Large O

Beverage

Mocha Black Coffee O Filter Coffee O

Order Coffee

Sachin has placed an order for small coffee of mocha type. This should cause the JavaScript code to send a request to the server-side for making this type of coffee. This order would be placed to

Coffee Maker #1.

Page 160: Ajax

Sample Flow – 2

Place your coffee order here:

Coffee

Maker #1

Busy

Coffee

Maker #2

Idle

While Sachin’s order is being

<script>

Var XmlHttp …

<!– Server side code for coffee making -->

<% if … %>

AJAX | Atul Kahate 160

Place your coffee order here:-ame: __Rahul_____________________

Size

Small O Medium Large O

Beverage

Mocha O Black Coffee O Filter Coffee

Order Coffee

While Sachin’s order is being processed, Rahul wants to

order a filter coffee of medium size. Since this is an

asynchronous application, it should allow Rahul to place his order. Rahul’s order will go to Coffee Maker #2. We have updated the status of Coffee

Maker#1, though.

Page 161: Ajax

Sample Flow – 3

Place your coffee order here:

Coffee

Maker #1

Idle

Coffee

Maker #2

Idle

When Sachin’s coffee is ready,

<script>

Var XmlHttp …

<!– Server side code for coffee making -->

<% if … %>

AJAX | Atul Kahate 161

Place your coffee order here:-ame: ________________________

Size

Small O Medium O Large O

Beverage

Mocha O Black Coffee O Filter Coffee O

Order Coffee

When Sachin’s coffee is ready, we send a message from the server-side code to indicate so. Also, the status of Coffee Maker #1 is changed back to Idle, indicating that it is ready

to take a fresh order.

Sachin: Your coffee is ready!

Page 162: Ajax

Thank you!

Any Questions?