Java Means Durga Soft: DURGA SOFTWARE SOLUTIONS, 202 HUDA Maitrivanam, Ameerpet, Hyd. PH: 040-64512786
Java Means Durga Soft: DURGA SOFTWARE SOLUTIONS, 202 HUDA Maitrivanam, Ameerpet, Hyd. PH: 040-64512786
-------------------------------------------------------------------------------------------------------
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 1
JAVA Means DURGA SOFT
AJAX
Introduction to AJAX:
AJAX is not a new programming language, but a new way to use existing standards.
AJAX is the art of exchanging data with a server, and update parts of a web page -
without reloading the whole page.
AJAX is about updating parts of a web page, without reloading the whole page.
Ajax can be used for creating rich, web-based applications that look and works like a
desktop application
With AJAX you can create better, faster, and more user-friendly web applications.
Ajax is the use of non standard XMLHttpRequest object to communicate with server side
scripts. It can send as well as receive information in a variety of formats including XML,
HTML, and even text files. Ajaxs most appealing characteristic, however, is its
asynchronous nature, which means that it can do all of this without having to refresh
the page. this allows you to update portions of a page based upon user events.
-------------------------------------------------------------------------------------------------------
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 2
JAVA Means DURGA SOFT
What is AJAX?
Optionally...
The "Asynchronous" word, means that the response of the server while be
processed when available, without to wait and to freeze the display of the page.
-------------------------------------------------------------------------------------------------------
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 3
JAVA Means DURGA SOFT
It is used mainly to build a fast, dynamic website, but also to save resources.
For improving sharing of resources, it is better to use the power of all the client
computers rather than just an unique server and network. Ajax allows performing
processing on client computer (in JavaScript) with data taken from the server.
The processing of web page formerly was only server-side, using web services
or PHP scripts, before the whole page was sent within the network.
But Ajax can selectively modify a part of a page displayed by the browser, and
update it without the need to reload the whole document with all images, menus,
etc...
For example, fields of forms, choices of user, may be processed and the result
displayed immediately into the same page.
The main purpose of Ajax is to provide a simple and standard means for a
webpage to communicate with the server without a complete page refresh
To illustrate the above scenario in detail, consider a simple registration form. You
have very likely experienced the frustration of having to try multiple user names
when registering for some new website. You fill out entire form, hit the submit
button, wait for the second or so, and then get the same form right back with a
message saying that the user name you have entered is not available. You try
another easy to remember username and find it is also not available. You repeat
the same process for several times until you pick some obscure username.
-------------------------------------------------------------------------------------------------------
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 4
JAVA Means DURGA SOFT
Ajax uses a programming model with display and events. These events
are user actions they call functions associated to elements of the web page.
XMLHttpRequest Object:
All modern browsers support the XMLHttpRequest object (IE5 and IE6 uses an
ActiveXObject).
The XMLHttpRequest object is used to exchange data with a server behind the
scenes. This means that it is possible to update parts of a web page, without
reloading the whole page.
How to create an XMLHttpRequest Object?
All modern browsers (IE7+, Firebox, Chrome, Safari, and Opera) have a built-in
XMLHttpRequest object.
Syntax for creating an XMLHttpRequest object:
-------------------------------------------------------------------------------------------------------
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 5
JAVA Means DURGA SOFT
variable=new XMLHttpRequest();
Old versions of Internet Explorer (IE5 and IE6) use an ActiveX Object:
variable=new ActiveXObject("Microsoft.XMLHTTP");
3. setRequestHeader (header_name,header_value)
4. overrideMimeType(text/xml);
-------------------------------------------------------------------------------------------------------
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 6
JAVA Means DURGA SOFT
The following tabular form gives the description of the above two methods.
Method Description
GET or POST?
GET is simpler and faster than POST, and can be used in most cases.
limitations)
-------------------------------------------------------------------------------------------------------
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 7
JAVA Means DURGA SOFT
xmlhttp.open("GET","demo_get.jsp",true);
xmlhttp.send();
If you want to send information with the GET method, add the information to the
URL
xmlhttp.open("GET","demo_get2.jsp?fname=sachin&lname=Tendulkar, true);
xmlhttp.send();
2. readyState
3.status
4. responseText
5. responseXML
1. onreadystatechange:
This property holds (or) contains the name of the javascript function
to be called whenever response from the server is received by the Ajax engine.
-------------------------------------------------------------------------------------------------------
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 8
JAVA Means DURGA SOFT
One for sending the request to the server and the other for receiving
Ex:-
function fun1()
{
var x=new ActiveXObject(Microsoft.XMLHTTP);
x.onreadystatechange=fun2;
------------------
x.open (-,-,-);
x.send ();
}
2. readyState:
-------------------------------------------------------------------------------------------------------
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 9
JAVA Means DURGA SOFT
3. status:
status attribute holds different status codes to know the status of the
response returned by the server
4. responseText:
This property holds the response data returned by the server for the
given request.
This property holds data(response) if the MIME type of the response is
Other than text/xml.
5.responseXML:
This property holds the response generated by the server for the
given request.
This property holds the data(response) only if the MIME type is
text/xml.
-------------------------------------------------------------------------------------------------------
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 10
JAVA Means DURGA SOFT
Procedure to develop Ajax code to interact with the web resource program
of web application:
When the key of keyboard is pressed and released to type a letter in the text
box, onKeyup event is raised and it calls the javascript function f1().
function f1 ()
{
if (window.XMLHttpRequest) // Object of the current window
{
var aeng = new XMLHttpRequest(); // code for IE7+, Firefox,
-------------------------------------------------------------------------------------------------------
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 11
JAVA Means DURGA SOFT
Step3: specify the name of the call back function to Ajax engine .
The function that executes automatically based on the events that are raised
is called callback function.
The above specified connection JavaScript function will be called
automatically by Ajax engine for each change that takes place in readyState
property value like 0-1, 1-2, 2-3, 3-4.
In the definition of callback function, we keep the logic to write the response
received by Ajax engine to webpage, but we make that logic execute only when
readyState property value is 4.
Step4: prepare request url having query string.
//read form data
var strng=document.f1.t1.value;
// frame request url
var url=test.jsp?q=+strng;
Step5: make Ajax engine send request to target web resource program
Asynchronously.
aeng.open (GET, url, true);
true: makes Ajax engine send asynchronous request to the target web
-------------------------------------------------------------------------------------------------------
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 12
JAVA Means DURGA SOFT
resource program
false: makes Ajax engine send synchronous request to the target web
resource program
Step6: develop target web resource program like servlet or jsp in the
Web application of server to process the request and generate the
response.
Step7: define callback function definition (java script function) having logic
to update webpage content when Ajax engines responseState is
4 and http response status code is 200.
Ex:
function connection()
{
If(aeng.readyState==4 || aeng.readyState==complete)
{
If(aeng.status==200)
{
------------
------------
}
}
}
var aengg;
if (window.XMLHttpRequest) // code for IE7+, Firefox,
Chrome, Opera, Safari
{
aeng = new XMLHttpRequest();
}
else if (window.ActiveXObject) // code for IE6-
{
try{
aeng = new ActiveXObject("Msxml2.XMLHTTP"); //for IE4+ to
IE6
} catch (Exception e)
{
aeng= new ActiveXObject(Microsoft.XMLHTTP);//for old IE
-------------------------------------------------------------------------------------------------------
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 13
JAVA Means DURGA SOFT
versions
}
}
Example Application 1:
The given below example describes how exactly Ajax works. And also it
displays all the matching countries while you type characters in the text box
provided on the form page of this application.in the process of displaying all the
matching countries, it asynchronously communicates with the server and updates
the page without causing the complete page reloading.
index.html
<html>
<head>
<script>
var xh;
function fun1()
{
if(window.ActiveXObject)
{
xh=new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
else if(window.XMLHttpRequest)
{
xh=new XMLHttpRequest();// code for IE7+, Firefox, Chrome, Opera, Safari
}
strng =document.f1.country.value;
alert(strng);
xh.onreadystatechange=connection;
xh.open("GET" , "test.jsp?q="+strng , true);
-------------------------------------------------------------------------------------------------------
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 14
JAVA Means DURGA SOFT
xh.send();
}
function connection()
{
if(xh.readyState==4)
{
document.getElementById("d1").innerHTML=xh.responseText;
}
}
</script>
</head>
<body>
<form name="f1">
country:<input type="text" name="country" onkeyup="fun1())"/>
</form>
<div id="d1"></div>
</body>
</html>
test.jsp
<%
String input=request.getParameter("q");
System.out.println(input);
Locale[] locales=Locale.getAvailableLocales();
System.out.println("locales created.........");
for(int i=0;i<locales.length;i++)
-------------------------------------------------------------------------------------------------------
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 15
JAVA Means DURGA SOFT
Locale locale=locales[i];
String country=locale.getDisplayCountry();
if(country.toUpperCase().startsWith(input.toUpperCase()))
choices.add(country);
Iterator it=choices.iterator();
while(it.hasNext())
String str=it.next().toString();
out.println(str+"<br>");
%>
Example Appliction2:
This example is also about updating the current webpage without reloading
the entire webpage by taking the support of Ajax. in this example, when you
select your state,all the districts belonging to that state will be added dynamically
to the second select box. And also when you select your district all your mandals
belonging to your selected district will be dynamically added to the third select
box
-------------------------------------------------------------------------------------------------------
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 16
JAVA Means DURGA SOFT
Index.html:
<html>
<head>
<script language="javascript">
var ajaxeng;
function fun1()
{
if(window.ActiveXObject)
{
ajaxeng=new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)
{
ajaxeng=new XMLHttpRequest();
}
strng =document.f1.sel1.value;
ajaxeng.onreadystatechange=fun2;
ajaxeng.open("GET","test.jsp?p1=" + strng , true);
ajaxeng.send();
}
function fun2()
{
var z=0;
removeAll();
if(ajaxeng.readyState==4 )
{
var xml=ajaxeng.responseXML;
var m=xml.documentElement;
-------------------------------------------------------------------------------------------------------
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 17
JAVA Means DURGA SOFT
var res=m.getElementsByTagName("dname")[z].childNodes[0].nodeValue;
while(res!=null)
{
addOption(res);
z++;
res= m.getElementsByTagName("dname")[z].childNodes[0].nodeValue;
}
}
}
function removeAll()
{
var x1=document.f1.sel2.length;
for(i=x1;i>=0;i--)
{
document.f1.sel2.options[i]=null;
}
}
function addOption(result)
{
var opt=document.createElement("OPTION");
opt.text=result;
opt.value=result;
document.f1.sel2.options.add(opt);
}
function fun3()
{
if(window.ActiveXObject)
-------------------------------------------------------------------------------------------------------
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 18
JAVA Means DURGA SOFT
-------------------------------------------------------------------------------------------------------
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 19
JAVA Means DURGA SOFT
{
ajaxeng=new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)
{
ajaxeng=new XMLHttpRequest();
}
strng =document.f1.sel2.value;
alert("name="+strng);
ajaxeng.onreadystatechange=fun4;
ajaxeng.open("GET","test1.jsp?p1=" + strng , true);
ajaxeng.send();
}
function fun4()
{
var z=0;
removeAll2();
if(ajaxeng.readyState==4 )
{
var xml=ajaxeng.responseXML;
varm=xml.documentElement;
var res=m.getElementsByTagName("mname")[z].childNodes[0].nodeValue;
while(res!=null)
{
addOption2(res);
z++;
res=m.getElementsByTagName("mname")[z].childNodes[0].nodeValue;
-------------------------------------------------------------------------------------------------------
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 20
JAVA Means DURGA SOFT
}
}
}
function removeAll2()
{
var x1=document.f1.sel3.length;
for(i=x1;i>=0;i--)
{
document.f1.sel3.options[i]=null;
}
function addOption2(result)
{
var opt=document.createElement("OPTION");
opt.text=result;
opt.value=result;
document.f1.sel3.options.add(opt);
}
</script>
</head>
<body>
<form name="f1">
Select your State: <select name="sel1" onchange="fun1()" >
<option value="10">Andhr Pradesh</option>
<option value="20" selected>Tamil Nadu</option>
<option value="30">Kerala</option>
<option value="40">Karnataka</option>
-------------------------------------------------------------------------------------------------------
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 21
JAVA Means DURGA SOFT
</select></br></br>Select your
District: <select name="sel2" onchange="fun3()">
<option>------select-------</option>
</select></br></br>
Mandals of your selected Distict:<select name="sel3">
<option>---------select-------</option>
</select>
</body>
</html>
Test.jsp:
%@ page import="java.sql.*" %>
<%
try
{
response.setContentType("text/xml");
String select=request.getParameter("p1");
int v=Integer.parseInt(select);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:ajax","ajax","ajax");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select dname from Districts where distid="+v);
-------------------------------------------------------------------------------------------------------
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 22
JAVA Means DURGA SOFT
out.println("<root>");
while(rs.next())
{
out.println("<dname>"+rs.getString(1)+"</dname>");
}
out.println("</root>");
con.close();
}catch(Exception e)
{
e.printStackTrace();
}
%>
test1.jsp:
<%@ page import="java.sql.*" %>
<%
try
{
response.setContentType("text/xml");
String select=request.getParameter("p1");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:ajax","ajax","ajax");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select mname from Mandals where
dname='"+select+"'");
out.println("<root>");
while(rs.next())
{
out.println("<mname>"+rs.getString(1)+"</mname>");
}
out.println("</root>");
con.close();
}
catch(Exception e)
{
e.printStackTrace();
}
%>
-------------------------------------------------------------------------------------------------------
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 23
JAVA Means DURGA SOFT
Example Application3:
This example describes what exactly asynchronous communication is
and how that can be achieved with the help of Ajax.
Links.html:
<html>
<head>
<script language="javascript">
var xh1,xh2;
function fun1()
{
if(window.ActiveXObject)
{
xh1=new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)
{
xh1=new XMLHttpRequest();
}
xh1.onreadystatechange=result1;
xh1.open("GET" , "srv1" , true);
xh1.send();
}
function fun2()
{
if(window.ActiveXObject)
{
xh2=new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)
{
-------------------------------------------------------------------------------------------------------
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 24
JAVA Means DURGA SOFT
xh2=new XMLHttpRequest();
}
xh2.onreadystatechange=result2;
xh2.open("GET" , "srv2" , true);
xh2.send();
function result1()
{
if (xh1.readyState==4 )
{
//document.getElementById("id1").style.color="blue";
document.getElementById("id1").innerHTML=xh1.responseText;
}
}
function result2()
{
if (xh2.readyState==4)
{
//document.getElementById("id2").style.color="red";
document.getElementById("id2").innerHTML=xh2.responseText;
}
}
</script>
<body>
<b> <a href="javascript:fun1()">link1</a>
<a href="javascript:fun2()">link2</a></b>
<h2><span id="id1"></span></br></br></br></h2>
<h1><span id="id2"></span></h1>
</body>
</html>.
LinkServlet1:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class LinkServlet1 extends HttpServlet
-------------------------------------------------------------------------------------------------------
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 25
JAVA Means DURGA SOFT
{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setHeader("cache-control","no-cache");
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
try{
Thread.sleep(10000);
}
catch(Exception e)
{
//e.printStackTrace();
System.out.println("exception has come");
}
pw.println("Result of link1");
pw.close();
}
}
SSLinkServlet2:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class LinkServlet2 extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
-------------------------------------------------------------------------------------------------------
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 26
JAVA Means DURGA SOFT
res.setHeader("cache-control","no-cache");
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
pw.println("Result of link2");
pw.close();
web.xml:
<web-app>
<servlet>
<servlet-name>dum1</servlet-name>
<servlet-class>LinkServlet1</servlet-class>
</servlet>
<servlet>
<servlet-name>dum2</servlet-name>
<servlet-class>LinkServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dum1</servlet-name>
<url-pattern>/srv1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>dum2</servlet-name>
<url-pattern>/srv2</url-pattern>
</servlet-mapping>
</web-app>
-------------------------------------------------------------------------------------------------------
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 27
JAVA Means DURGA SOFT
Drawbacks of AJAX:-
Since data to display are loaded dynamically, they are not part of
the page, and the keywords inside are not used by search engines.
The asynchronous mode may change the page with delays (when
the processing on the server take some times), this may be
disturbing.
-------------------------------------------------------------------------------------------------------
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 28
JAVA Means DURGA SOFT
-------------------------------------------------------------------------------------------------------
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 29
JAVA Means DURGA SOFT
-------------------------------------------------------------------------------------------------------
DURGA SOFTWARE SOLUTIONS ,202 HUDA Maitrivanam, Ameerpet , Hyd. Ph: 040-64512786 Page 30