I will demonstrate how to develop a simple AJAX Application for beginners
In the context of fast rendering of the screen without refreshing, the AJAX comes into picture. In scenarios, like
on selecting one select box another select box has to populated by making a AJAX call to server, I will show you how to achieve it.
Step 1 : Servlet class
1) Prepare a Java servlet class Let's say GetDataServlet with necessary methods which we need to make a call
2) You need to use out.print() to construct the response
3) prepare the servlet-mapping and servlet in web.xml let's say as getData
Step 2 : JSP
1) Construct the jsp. Here I have 2 select boxes. one which is already populated using bean and second one to be done using AJAX
sample code for select box 1
<select name="loginNameSelect" id="loginSelect" onchange="change()">
<% ModelUtility modelUtil = new ModelUtility();
List<String> uList = modelUtil.getUserList();
Iterator itr = uList.iterator();
while(itr.hasNext()){
String val = (String)itr.next();
%>
<option value=<%=val%>><%=val%></option>
<% } %>
</select>
In my case I have ModelUtility bean, which returns me the list of users
sample code for select box 2
%<select name="ajaxPopulate" id="ajaxPopulate"%>%</select%>
Step 3 Javascript
If you see, I have attached a javascript function for onchange event on select box 1. Here is where we make a AJAX call to our servlet (GetDataServlet).
Once we make a call to server, the response will be returned in xmlhttp response either as simple text or XML which ever fromat we outputted in servlet
Here you can parse the response and construct the elements of select box 2
Sample code goes like this
function change()
{
var answer = document.getElementById('loginSelect').value;
var http = new XMLHttpRequest();
var url = "getData";
var params = "loginName="+answer;
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
var responseString = http.responseText;
var arrUsers = responseString.split(',');
var select = document.getElementById("ajaxPopulate");
select.options.length = 0;
for(var i=0;i
select.options.add(new Option(d, i))
}
}
}
http.send(params);
}
With this the data gets populated by making a call to getDataServlet
I am available for any clarification
A Ram Prasad