1) The document discusses Asynchronous JavaScript and XML (AJAX) which allows for asynchronous communication between a browser and server without requiring the user to wait for processing a request.
2) Traditional HTTP processing uses synchronous request-response pairs while AJAX uses asynchronous JavaScript calls to update portions of a page without refreshing.
3) The key aspects of AJAX covered are the XMLHttpRequest object, opening the object to specify the request, handling the response, and properties/methods of the object. Server-side code can also be invoked using AJAX.
2. Traditional HTTP Processing
Request-
response pairs
(Synchronous Web Server
in nature)
Web
Brows
er
AJAX | Atul Kahate 2
3. AJAX-based Processing
Web Server
Asynchronous
JavaScript operation
<script>
Web function
Brows abc() { …}
er
Update
AJAX | Atul Kahate 3
4. What is AJAX?
Asynchronous JavaScript and XML
Allows for asynchronous communication
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
AJAX | Atul Kahate 4
5. 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
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.
AJAX | Atul Kahate 5
6. 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
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.
AJAX | Atul Kahate 6
7. 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
9. 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
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
AJAX | Atul Kahate 9
10. The XMLHttpRequest Object
Alternative for HTML forms
Used to communicate with the server side
code, from inside a browser
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
AJAX | Atul Kahate 10
11. AJAX Steps
1. Create a request object
2. Tell the request object where to send
the request
3. Tell the object what to do when the
request is answered
4. Tell the object to make a request
AJAX | Atul Kahate 11
12. 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
control)
Accordingly, coding changes across
browser versions as well
AJAX | Atul Kahate 12
15. 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;
if (window.XMLHttpRequest) { // Non-IE browser
XMLHttpRequestObject = new XMLHttpRequest ();
}
IE code
else if (window.ActiveXObject) { // IE browser
XMLHttpRequestObject = new ActiveXObject
("Microsoft.XMLHTTP");
}
AJAX | Atul Kahate 15
16. Creating an XMLHttpRequest
Object Using JavaScript – 2
Now start writing HTML as usual, after
checking for the presence of the
XMLHttpRequest object
if (XMLHttpRequestObject) {
document.write ("<h1>Welcome to AJAX</h1>");
}
AJAX | Atul Kahate 16
17. 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 ();
}
else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject ("Microsoft.XMLHTTP");
}
if (XMLHttpRequestObject) {
document.write ("<h1>Welcome to AJAX</h1>");
}
</script>
</head>
<body>
</body>
</html>
AJAX | Atul Kahate 17
20. <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>
<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
AJAX | Atul Kahate 20
24. Step 2: Tell the object where to
send the request (Open the
XMLHttpRequest Object)
25. Open the XMLHttpRequest
Object – 1
Opening the XMLHttpRequest object
prepares it for use to fetch data from
the server
Use the open method
Mandatory parameters
Method type (GET, PUT, POST)
URL
AJAX | Atul Kahate 25
26. 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, pass
1. The name of a text file (data.txt) to this function
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
AJAX | Atul Kahate 26
27. 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) {
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> AJAX | Atul Kahate 27
<H1>Fetching data with AJAX</H1>
28. Step 3: What to do when the
request is answered (Get Ready
to Download)
29. 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:
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
AJAX | Atul Kahate 29
30. 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
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
31. 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) {
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> AJAX | Atul Kahate 31
<!-- Add a form with a Display Message button connected to a JavaScript function named getData -->
33. 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 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
34. Properties and Methods – 2
Property/Method Description
getAllResponseHeade Gets all headers in a name/value format
rs ()
getResponseHeader Returs header value corresponding to a specified header
(header name) name
open (method, url, Initializes the request for sending to the server
asynch)
setRequestHeader Adds an HTTP header to the request with a specified value
(name, value)
send (body) Initiates the request to the server
AJAX | Atul Kahate 34
35. Step 4: Tell the object to make a
request (Download Data with the
XMLHttpRequest Object)
36. 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
passed
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
AJAX | Atul Kahate 36
37. 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 ();
}
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> AJAX | Atul Kahate 37
<!-- Add a form with a Display Message button connected to a JavaScript function named getData -->
42. 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
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
AJAX | Atul Kahate 42
43. 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 ();
}
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> AJAX | Atul Kahate 43
<!-- Add a form with a Display Message button connected to a JavaScript function named getData -->
45. 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.xml
from the server
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
AJAX | Atul Kahate 45
46. 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 ();
}
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> AJAX | Atul Kahate 46
</head>
48. 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 sandwiches
Add the code to pass this sandwiches array
variable to a new function, listSandwiches
At this point, have the listSandwiches
function only display a message Got the
sandwiches
Later, we will see how to extract the XML contents
AJAX | Atul Kahate 48
49. 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 ();
}
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");
}
} AJAX | Atul Kahate 49
XMLHttpRequestObject.send (null);
}
51. Extracting Data from XML
Elements – 1
We can extract data from XML elements
by using JavaScript
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
AJAX | Atul Kahate 51
52. 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
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
AJAX | Atul Kahate 52
53. 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
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 new
operator
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
AJAX | Atul Kahate 53
54. 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 ();
}
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);
} AJAX | Atul Kahate 54
}
56. 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
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
AJAX | Atul Kahate 56
57. 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 ();
}
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) { AJAX | Atul Kahate 57
XMLHttpRequestObject.open ("GET", "ajax10.jsp?type=2");
58. 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) {
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>");
%>
AJAX | Atul Kahate 58
60. 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
referred to, we have a problem
Solution: Use multiple XMLHttpRequest objects
Ref:
D:tomcatwebappsexamplesajaxmultipleXMLHttpR
equest
AJAX | Atul Kahate 60
61. 11.html
<html>
<head>
<title>Using two XMLHttpRequest Objects</title>
<script type = "text/javascript">
var menu;
var XMLHttpRequestObject1 = false;
// alert ("start");
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 () {
AJAX | Atul Kahate
if (XMLHttpRequestObject1.readyState == 4 && XMLHttpRequestObject1.status == 200) { 61
var xmlDocument = XMLHttpRequestObject1.responseXML;
menu = xmlDocument.getElementsByTagName ("menuitem");
62. menu1.xml
<?xml version = "1.0"?>
<menu>
<menuitem>Main
course</menuitem>
<menuitem>Fasting</menuitem>
<menuitem>Salad and
Fruits</menuitem>
</menu>
AJAX | Atul Kahate 62
64. Ajax Calculator
Write a simple Ajax application to
accept two integers from the user and
display their sum on the same screen
NetBeans - AjaxCalculator
70. Changes to be done
Now allow all operations (add, subtract,
multiply, divide)
AJAX | Atul Kahate 70
71. index-2.html
Ajax Calculator
Enter integer values below
Value 1 Value 2 Operation (+ - * or /)
Result AJAX | Atul Kahate 71
72. ajax-2.js
var req;
function computeResult () {
var num_1 =
document.the_form.field_1.value;
var num_2 =
document.the_form.field_2.value;
var operator =
AJAX | Atul Kahate 72
document.the_form.field_3.value;
73. AllOperationsServlet
/*
* To change this template, choose
Tools | Templates
* and open the template in the editor.
*/
package com.ajax.servlet;
import java.io.*; | Atul Kahate
AJAX 73
import java.net.*;
74. AJAX Application
Character Decoder – Allow the user to enter a
character and show its ASCII value
(Netbeans – AJAX-Character-Decoder-1)
75. 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>
<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> AJAX | Atul Kahate 75
</body>
76. 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) {
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 ();
}
AJAX | Atul Kahate 76
function clear () {
var key = document.getElementById ("key");
78. 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.*;
/**
*
* @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) { AJAX | Atul Kahate 78
// Extract first character from key as int, and convert it into a string
int keychar = key.charAt(0);
80. Exercise
Modify the above example to allow the
user to type. As soon as the user types
a character, get all the matching entries
starting with that character and display
back to the user
NetBeans: Ajax-Character-Decoder-2
AJAX | Atul Kahate 80
81. 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>
<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>
AJAX | Atul Kahate
<input type = "text" id = "decimal" readonly value = ""> 81
</td>
</tr>
86. Requirements
User types an account number. Show
corresponding account balance. Also
show one of the following messages:
Success
Account number is invalid
Error in processing
AJAX | Atul Kahate 86
90. Account.java
/*
* To change this template, choose
Tools | Templates
* and open the template in the editor.
*/
package com.ajax.serverside;
AJAX | Atul Kahate 90
/**
92. 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
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
AJAX | Atul Kahate 92
93. Traditional Application
Example
Web form that JSP
submits the returns
request to a the latest
JSP page number
of copies
sold
AJAX | Atul Kahate 93
95. Execution Steps – 2
Reload!
Server sends
a response
now
AJAX | Atul Kahate 95
96. Code for the AJAX Version
Several basic concepts are needed to
understand this, and hence, we shall
study it after the theoretical and
conceptual overview
Come back to the next slide later, once
the basic concepts are finished
AJAX | Atul Kahate 96
97. Application Design
Our code would have the following
JavaScript functions:
getBooksSold ()
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
AJAX | Atul Kahate 97
99. Add JavaScript Now
On click of the
button, call a
JavaScript
function
getBooksSold ()
AJAX | Atul Kahate 99
100. The getBooksSold () Function
Create a new request by calling the
createRequest () function
Specify the URL to receive the updates
from
Set up the request object to make a
connection
Request an updated number of books
sold
AJAX | Atul Kahate 100
102. createRequest () Function
This function would simply try to create an
instance of the XMLHttpRequest object, as
per the browser type
function createRequest () {
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest ();
}
else
if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject ("Microsoft.XMLHTTP");
}
}
AJAX | Atul Kahate 102
103. Now Modify getBooksSold ()
function getBooksSold () {
createRequest ();
var url = "getUpdatedBookSales.jsp";
XMLHttpRequestObject.open ("GET", url);
…
This would call getUpdatedBookSales.jsp
We want to process the response sent by this
JSP now
AJAX | Atul Kahate 103
104. Now, Process the Results
function getBooksSold () {
createRequest ();
var url = "getUpdatedBookSales.jsp";
XMLHttpRequestObject.open ("GET", url);
XMLHttpRequestObject.onreadystatechange = updatePage;
XMLHttpRequestObject.send (null);
How does this work?
AJAX | Atul Kahate 104
105. updatePage ( ) Needs to do
this
Updated
number of
books sold
JavaScript
Update
these now
AJAX | Atul Kahate 105
106. When to call updatePage ()?
When this function receives a response
from JSP, it needs to update the values
on the screen, making this
asynchronous
Hence, we have:
XMLHttpRequestObject.onreadystatechang
e = updatePage;
Call updatePage () when a response is
received
AJAX | Atul Kahate 106
107. updatePage () Function – 1
First read the response sent by the JSP
page
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
AJAX | Atul Kahate 107
108. updatePage () Function – 2
function updatePage () {
var newTotal = XMLHttpRequestObject.responseText;
var booksSoldElement = document.getElementById
("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
AJAX | Atul Kahate 108
109. updatePage () Function – 3
function updatePage () {
var newTotal = XMLHttpRequestObject.responseText;
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
AJAX | Atul Kahate 109
110. What should the JSP do?
Normally, the JSP would return a full
HTML
Now, it has to return a single number:
number of books sold at this moment
Hence, the JSP just has:
out.print (300);
AJAX | Atul Kahate 110
111. 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;
i<40000; i++);
out.print ("300");
%>
Now rerun the application
AJAX | Atul Kahate 111
112. Modify the example to expect
an XML from the JSP
D:tomcatwebappsajaxbooks-
xml-version
AJAX | Atul Kahate 112
114. Requirements – 1
When the user clicks on the button, the
browser should send a request to the
JSP 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
119. User ID – Case Study
NetBeans – Ajax-Misc
AJAX | Atul Kahate 119
120. Requirements
Accept a user ID from the user for new
ID creation
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
122. user.css
/*
Document : user
Created on : Jun 9, 2008, 2:30:51
PM
Author : atulk
Description:
Purpose of the stylesheet follows.
*/ AJAX | Atul Kahate 122
123. user.js
var req;
function getUserID () {
var userID =
document.the_form.field_1.value;
// alert ("inside JS");
AJAX | Atul Kahate 123
var url = "getUserID.jsp?userID=" +
127. What is JSON?
Alternative to XML when we do not
need advanced capabilities of XML, such
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
128. 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)
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
129. 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
131. 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
132. 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-
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
133. 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
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
134. JSON Example (Same Books
Example now in JSON)
D:tomcatwebappsajaxbooks-
json-version
AJAX | Atul Kahate 134
139. Requirements
User would type
the phone number
here. Once
finished, the
customer’s address
details should be
shown
automatically.
AJAX | Atul Kahate 139
140. 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
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.
AJAX | Atul Kahate 140
141. HTML for the Basic Page
pizzaDelivery.html
<html>
<head>
<title>Pizza Delivery Page</title>
<link rel="stylesheet" type="text/css"
href="pizzaDelivery.css" />
</head>
<body>
<form method="POST" action="placeOrder.jsp">
AJAX | Atul Kahate 141
<p>Enter your phone number:
142. CSS for the Basic Page
pizzaDelivery.css
body {
font-family: Verdana;
background-color: black;
}
p{
font-size: large;
color: red;
}
AJAX | Atul Kahate 142
textarea {
143. 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
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 …
AJAX | Atul Kahate 143
145. Writing the getCustomerInfo
() Function – 1
We need to obtain the value of the
phone number entered by the user
function getCustomerInfo () {
var phone = document.getElementById
(“phone”).value;
AJAX | Atul Kahate 145
146. Writing the getCustomerInfo
() Function – 2
Next, we want to request for the
customer’s address
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.
AJAX | Atul Kahate 146
147. Writing the getCustomerInfo
() Function – 3
function getCustomerInfo ( ) {
var phone = document.getElementById
(“phone”).value;
var url = “lookupCustomer.jsp?phone=“ + escape
(phone);
request.open (“GET”, url, true);
request.onreadystatechange = updatePage;
request.send (null);
}
AJAX | Atul Kahate 147
148. Full HTML
(C:tomcatwebappsexamples
AJAXpizza)
<html>
<head>
<title>Pizza Delivery Page</title>
<link rel="stylesheet" type="text/css"
href="pizzaDelivery.css" />
<script language = "javascript" type =
"text/javascript">
AJAX | Atul Kahate 148
var XMLHttpRequestObject = null;
149. JSP Page
<%
for (int i=1; i<30000; i++)
for (int j=1; j<30000; j++)
for (int k=1; k<5; k++);
out.print ("Pune");
%>
AJAX | Atul Kahate 149
150. Exercise
Modify the JSP page to read the
address from a database
AJAX | Atul Kahate 150
151. Modified JSP
<%@page import="java.sql.*" %>
<%@page import="java.util.*" %>
<%
// Open Database Connection
Class.forName
("sun.jdbc.odbc.JdbcOdbcDriver");
// Open a connection to the database
Connection con Atul Kahate
AJAX |
= 151
DriverManager.getConnection("jdbc:odbc:cust
153. User Interface
Coffee Maker Coffee Maker
#1 #2
Idle Idle
Place your coffee order here:
ame: ________________________
Size
Small O Medium O Large O
Beverage
Mocha O Black Coffee O Filter Coffee O
Order Coffee
AJAX | Atul Kahate 153
154. Requirements
Initially, both Coffee Maker #1 and #2
would be idle
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
AJAX | Atul Kahate 154
155. Application Structure
Coffee maker HTML
Take orders, report status of the two makers
JavaScript code
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
AJAX | Atul Kahate 155
156. Application Flow – 1
The Web page should display the status
of both coffee makers (Idle initially)
Coffee Coffee
Maker #1 Maker #2
Idle Idle
Place your coffee order here:
ame: ________________________
Size
Small O Medium O Large O
Beverage
Mocha O Black Coffee O Filter Coffee O
Order Coffee
AJAX | Atul Kahate 156
157. Application Flow – 2
<!– Server side code
for coffee making -->
<% if … %>
…
Coffee Coffee <script>
Maker #1 Maker #2
Var XmlHttp …
Idle Idle
…
The JavaScript should be
Place your coffee order here: able to send requests to
ame: ________________________
brew coffee to the coffee
Size maker script on the server
and handle response
Small O Medium O Large O received from the server.
It also needs to update
Beverage the status of the coffee
maker, and let the users
Mocha O Black Coffee O Filter Coffee O
know when the coffee is
Order Coffee
ready.
AJAX | Atul Kahate 157
158. Application Flow – 3
<!– Server side code
for coffee making -->
<% if … %>
…
Coffee Coffee <script>
Maker #1 Maker #2
Var XmlHttp …
Idle Idle
…
The server-side code is quite
Place your coffee order here: simple. It takes a request to
ame: ________________________
brew coffee along with the
Size cup size, coffee type, and
name of the person. Once the
Small O Medium O Large O coffee is ready, it sends back
the response along with the
Beverage name of the person who
placed the order.
Mocha O Black Coffee O Filter Coffee O
Order Coffee
AJAX | Atul Kahate 158
159. Sample Flow – 1
<!– Server side code
for coffee making -->
<% if … %>
…
Coffee Coffee <script>
Maker #1 Maker #2
Var XmlHttp …
Idle Idle
…
Sachin has placed an order for
Place your coffee order here: small coffee of mocha type.
ame: __Sachin_____________________
This should cause the
Size JavaScript code to send a
request to the server-side for
Small Medium O Large O making this type of coffee.
This order would be placed to
Beverage Coffee Maker #1.
Mocha Black Coffee O Filter Coffee O
Order Coffee
AJAX | Atul Kahate 159
160. Sample Flow – 2
<!– Server side code
for coffee making -->
<% if … %>
…
Coffee Coffee <script>
Maker #1 Maker #2
Var XmlHttp …
Busy Idle
…
While Sachin’s order is being
Place your coffee order here: processed, Rahul wants to
ame: __Rahul_____________________
order a filter coffee of medium
Size size. Since this is an
asynchronous application, it
Small O Medium Large O should allow Rahul to place
his order. Rahul’s order will go
Beverage to Coffee Maker #2. We have
updated the status of Coffee
Mocha O Black Coffee O Filter Coffee
Maker#1, though.
Order Coffee
AJAX | Atul Kahate 160
161. Sample Flow – 3
<!– Server side code
for coffee making -->
<% if … %>
…
Coffee Coffee <script>
Maker #1 Maker #2
Var XmlHttp …
Idle Idle
…
When Sachin’s coffee is ready,
Place your coffee order here: we send a message from the
ame: ________________________
server-side code to indicate
so. Also, the status of Coffee
Sachin: Your coffee is ready!
Size
Maker #1 is changed back to
Small O Medium O Large O Idle, indicating that it is ready
to take a fresh order.
Beverage
Mocha O Black Coffee O Filter Coffee O
Order Coffee
AJAX | Atul Kahate 161