Sie sind auf Seite 1von 12

AJAX volume 1

Introduction to
AJAX
Using AJAX in combination with JSP
J. M. V. Swamy Naidu, M.C.A.

[2009
]

[NaiduMCA1@gmail.com]
Introduction to AJAX 2009

A JAX stands for Asynchronous Javascript And XML.

• What You Should Already Know


Before you continue you should have a basic understanding
of the following:

 HTML / XHTML
 JavaScript

• If you want to study these subjects first, find the tutorials


at www.w3schools.com.
• AJAX is not a new programming language, but a technique
for creating better, faster, and more interactive web
applications.
• With AJAX, your JavaScript can communicate directly with
the server, using the JavaScript’s XMLHttpRequest
object. With this object, your JavaScript can trade data
with a web server, without reloading the page.
• AJAX uses asynchronous data transfer (HTTP requests)
between the browser and the web server, allowing web
pages to request small bits of information from the server
instead of whole pages.
• The AJAX technique makes Internet applications smaller,
faster and more user-friendly.
• AJAX is a browser technology independent of web server
software.
• AJAX is Based on Web Standards

 JavaScript
 XML [Extensible Markup Language]
 HTML [Hyper Text Markup Language]
 CSS [Cascading Style Sheet]

J. M. V. Swamy Naidu, M.C.A.


Introduction to AJAX 2009

• The web standards used in AJAX are well defined, and


supported by all major browsers. AJAX applications are
browser and platform independent.
• AJAX is About Better Internet Applications.

• Web applications have many benefits over desktop


applications; they can reach a larger audience, they are
easier to install and support, and easier to develop.
• However, Internet applications are not always as "rich"
and user-friendly as traditional desktop applications.
• With AJAX, Internet applications can be made richer and
more user-friendly.
• You Can Start Using AJAX Today there is nothing new to
learn.
• AJAX is based on existing standards. These standards
have been used by most developers from several years.

• AJAX Uses HTTP Requests

 In traditional JavaScript coding, if you want to get any


information from a database or a file on the server, or
send user information to a server, you will have to make
an HTML form and GET or POST data to the server. The
user will have to click the "Submit" button to send/get the
information, wait for the server to respond, and then a
new page will load with the results.

 Because the server returns a new page each time the user
submits input, traditional web applications can run slowly
and tend to be less user-friendly.

 With AJAX, your JavaScript communicates directly with the


server, through the JavaScript XMLHttpRequest object.

 With an HTTP request, a web page can make a request to,


and get a response from a web server - without reloading
the page. The user will stay on the same page, and he or

J. M. V. Swamy Naidu, M.C.A.


Introduction to AJAX 2009

she will not notice that scripts request pages, or send data
to a server in the background.

• The XMLHttpRequest Object

• By using the XMLHttpRequest object, a web developer


can update a page with data from the server after the
page has been loaded!

• AJAX was made popular in 2005 by Google (with Google


Suggest).

• Google Suggest is using the XMLHttpRequest object to


create a very dynamic web interface: When you start
typing in Google's search box, a JavaScript sends the
letters off to a server and the server returns a list of
suggestions.

• The XMLHttpRequest object is supported in Internet


Explorer 5.0+, Safari 1.2, Mozilla 1.0 / Firefox, Opera 8+,
and Netscape 7.

• Internet Explorer supports the AJAX in the form of an


ActiveXObject, and it is named as Micosoft.XMLHTTP

• A Simple example for AJAX usage:

Here we need two files to explain how to use the AJAX


in web development.
These two files are named as
• AJAXRequestHTML.htm
• AJAXResponseJSP.jsp

J. M. V. Swamy Naidu, M.C.A.


Introduction to AJAX 2009

The two files are self descriptive by their names, the


first one is a simple HTML file that generates and sends the
http request to the web server.
Where as the second is a JSP file that is resides on the
server side and runs on the server in response to the http
request received by the web server.
First we write code for the AJAXRequestHTML.htm and
then AJAXResponseJSP.jsp files in the same order as they are
accessed by the client.
 Source code for the AJAXRequestHTML.htm file:

The source code for HTML file is divided into 4


parts/functions for the better understanding purpose.
1. Browser checker and XMLHttpRequest object
creator.
2. Sender request to server.
3. Response handler from server.
4. Response data displayer.
Here we use two global variables,
1. request_URL
2. request_Object

1. Browser checker and XMLHttpRequest object


creator:
• Implementations for the XMLHTTPRequest object
are different for different browsers.
• For Mozilla Firefox it is implemented as
XMLHttpRequest object.
• For Internet Explorer it is implemented as
Microsoft.XMLHTTP or Msxml2.XMLHTTP
• So you need to check for the browser first.

<script type=”text/javascript”>
function createObject() {
request_URL =
“http://localhost:8080/AJAXResponseJSP.jsp?”;
var temp = “”;
if( window.XMLHttpRequest ) {
temp = new XMLHttpRequest();

J. M. V. Swamy Naidu, M.C.A.


Introduction to AJAX 2009

}
if( window.ActiveXObject ) {
temp = new
ActiveXObject(Microsoft.XMLHTTP);
}
return temp;
}
</script>

As you seen above the code first checks for


the browser type and then create appropriate
request object and finally returns the object
created.

2. Send requsest to Server:

Before going to write the code for this function you


might have to meet some of the AJAX methods,
they are:
open(): Establishes the connection to the
server.
send(): Send the data to the server.
abort(): Aborts the current transmission of
data and
terminates the connection.

open():
This is the method that actually establishes
the communication with the server. It takes three
parameters, they are:
1. Type of Method: It either GET or POST.
2. Request handler’s URL: The URL for the
request handler on the server’s side that
generates the response.
3. Mode of transmission: It’s a Boolean value
that indicates the Asynchronous
transmission true or false. By default it is
true.

J. M. V. Swamy Naidu, M.C.A.


Introduction to AJAX 2009

Caution: Care must be taken when giving URL value of the


request handler that resides on the server side. Here I
place these two files in the same directory that was the
default directory for my server to sees for the files.
For example in Tomcat, the file AJAXrequestHTML.htm
is placed in the folder webapps/examples/jsp, now it can
be accessible by the URL from the browser
http://localhost:8080/examples/jsp/AJAXRequestHTM
L.htm.
Now the request handler AJAXResponseJSP.jsp is also
placed in the same folder as the AJAXRequestHTML.htm,
then we use the URL from the Javascript code as
http://localhost:8080/examples/jsp/AJAXResponseJSP
.jsp
If the path value is changed for the request handler the
appropriate value should be provided for the path that
should be resolved correctly.

Some properties we are using here are:


onreadystatechange.
readyState.
status.
responseText.

function makeAndSendRequest() {
request_Object = createObject();
request_Object.open(“GET”, request_URL,
true);
request_Object.onreadystatechange =
responseHandler;
request_Object.send(null);
}

Here,
In the first line of the code it’s a call to the
method createObject(), that we’ve already
created, that returns the XMLHttpRequest object.
In the second line, it’s a call to the AJAX
method open using GET method.
In the third line, it’s the assignment of the
value that is the name of the method [don’t use
any parenthesis here] used whenever the ready

J. M. V. Swamy Naidu, M.C.A.


Introduction to AJAX 2009

state changes a call to the assigned method is


performed.
In the last and fourth line, there is a call to
the send method with null value [it requires value
when using POST method instead of GET].

3. Response Handler from server:

The following code is executed whenever the


desired values for the status and readyState
properties are assigned.
For example,
status values are 200 – resource found, 404 –
resource not found, 500 – server side error.
readyState value is,
0– request not prepared yet.
1-Request initialized.
2-Preparing request with data.
3-Prepare request for submission.
4-Request submitted successfully.

So here we need the value for the status is 200 and for
the readyState are 4. Now it’s time to write code.

function responseHandler() {
if( request_Object.readyState == 4 ) {
if( request_object.status == 200 ) {

displayResponse(request_Object.responseText);
}
}
}

4. Display response:

function displayResponse(val) {

J. M. V. Swamy Naidu, M.C.A.


Introduction to AJAX 2009

//Here divX is the id of the div tag inside


the //AJAXRequestHTML.htm file, we set the
value for that.

document.getElementById(“divX”).innerHTML
= “<b>” + val + “</b>”;
}

Here we are trying to set the innerHTML value for the


div tag identified by it’s unique id divX.

Now the integration of the above parts/segments of code


into a single html file is,

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01


Transitional//EN”>
<html>
<head>
<title> AJAX Request Data Page</title>
<script type=”text/javascript”>
var request_URL = “”; //script Global variable
var request_Object = “”; //script Global variable
function createObject() {
request_URL =
“http://localhost:8080/AJAXResponseJSP.jsp?”;
var temp = “”;
if( window.XMLHttpRequest ) {
temp = new XMLHttpRequest();
}
if( window.ActiveXObject ) {
temp = new ActiveXObject(Microsoft.XMLHTTP);
}
return temp;
}
function makeAndSendRequest(nData) {
request_Object = createObject();
var data = request_URL + “data=” + nData;
request_Object.open(“GET”, data, true);

J. M. V. Swamy Naidu, M.C.A.


Introduction to AJAX 2009

request_Object.onreadystatechange =
responseHandler;
request_Object.send(null);
}
function responseHandler() {
if( request_Object.readyState == 4 ) {
if( request_Object.status == 200 ) {
displayResponse(request_Object.responseText);
}
}
}
function displayResponse(val) {
//Here divX is the id of the div tag inside the
//AJAXRequestHTML.htm file, we set the value for that.

document.getElementById(“divX”).innerHTML = “<b>”
+ val + “</b>”;
}
</script>
</head>
<body bgcolor=”#ffffff” text=”#ff00ff”>
<form action=”” method=””>
<table align=”center”>
<tr>
<td>Enter your name:</td>
<td><input type=”text”
name=”myName” /></td>
</tr>
<tr><td colspan=”2”><input type=”button”
value=”Send”
onclick=”makeAndSendRequest(myName.value)” /></td>
</tr>
</table>
</form>
<div id=”divX” align=”center”><div>
</body>
</html>

J. M. V. Swamy Naidu, M.C.A.


Introduction to AJAX 2009

Notice: If you copy and paste the content from here, there
may be a problem with the double quotes that makes coding
error. Please check them or retype them in the corresponding
html and jsp pages.

 Source code for the AJAXResponseJSP.jsp file:

Here my intension is how to use the AJAX in


combination with JSP, so you can elaborate it in detail.

<%@ page language=”java” session=”false” %>


<%
String myName = request.getParameter(“data”);
// data, It is the property name that we are
passing along with the request
response.setContentType(“text/html”);
response.setHeader(“Cache-Control”,”no-cache”);
response.getWriter().write(“Hello “ + myName );
out.println( “<br />Congratulations it works
well!”);
%>
<%= “<br />Thank you” %>

POST Mode for the encrypted form of data


transmission:

The usage of POST method is different from the


usage of GET method, the difference is that the
encryption of the data that is to be transmitted. For this
there is another article that demonstrates how to use
the POST mode of transmission of data in combination
with JSP with title “AJAX with JSP using POST mode
of transmission”.

J. M. V. Swamy Naidu, M.C.A.


Introduction to AJAX 2009

Regards
Naidu, MCA
For any queries or suggestions on this article
contact me @
NaiduMCA1@gmail.com
http://www.NaiduMCA.co.cc

J. M. V. Swamy Naidu, M.C.A.