I am writing here a very simple ajax program. That will take roll number from jsp page, hit serlvlet, come back with result as XML, parse in javascript and will show on jsp page.
1. ShowStudentInfo.jsp
<html><head>
<title>Binod Java Solution AJAX </title>
<script type="text/javascript">
var request; function getName(){
var roll = document.getElementById("roll").value;
var url = "http://localhost:8080/blog_demo/StudentInfo?roll="+roll;
if(window.ActiveXObject){ request = new ActiveXObject("Microsoft.XMLHTTP"); }
else if(window.XMLHttpRequest){ request = new XMLHttpRequest(); } request.onreadystatechange = showResult;
request.open("POST",url,true);
request.send();
}
function showResult(){
if(request.readyState == 4){
var response = request.responseXML;
var students = response.getElementsByTagName("Student");
var student = students[0];
document.getElementById("NamelH1").innerHTML = student.getElementsByTagName("Name")[0].text;
document.getElementById("HostelH1").innerHTML = student.getElementsByTagName("Hostel")[0].text;
document.getElementById("ContactH1").innerHTML = student.getElementsByTagName("Contact")[0].text;
}
}
</script>
</head>
<body><h2> GET STUDENT INFO </h2>
<br> Enter Roll Number <input type="text" id="roll">
<input type="button" value="Get Name" onclick="getName();"/>
<br> Name : <span id="NamelH1"></span> <br
> Hostel : <span id="HostelH1"></span> <br
> Contact : <span id="ContactH1"></span> <br>
</body>
</html>
2. Servlet java file StudentInfo.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class StudentInfo extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
static final long serialVersionUID = 1L;
public StudentInfo() { super(); }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("**** STUDENT INFO ****");
String roll = request.getParameter("roll");
PrintWriter out = response.getWriter();
response.setContentType("text/xml");
System.out.println(getResult(roll)); out.println(getResult(roll));
}
public String getResult(String roll){
String name = "";
String hostel = "";
String contact = "";
if(roll.equalsIgnoreCase("110")){
name = "Binod Kumar Suman"; hostel = "Ganga"; contact = "999999999";
} else if(roll.equalsIgnoreCase("120")){
name = "Pramod Kumar Modi"; hostel = "Godawari"; contact = "111111111111";
} else{ name = "Roll Number not found"; }
String result = "<Students>";
result += "<Student>"; result += "<Name>" + name + "</Name>";
result += "<Hostel>" +hostel + "</Hostel>";
result += "<Contact>" +contact + "</Contact>";
result += "</Student>"; result += "</Students>";
return result;
}
}
Now simple run your JSP page and put the roll number like 110, it will work.
http://localhost:8080/Ajax_Demo/ShowStudentInfo.jsp
If you have any question or suggestion, please put your commnets.
Saturday, May 9, 2009
Subscribe to:
Post Comments (Atom)

First of all thanks for easy example. Could you please provide any easy example for Ajax with JSP. Thanks.
ReplyDeleteThanks for your appreciation. I will put one more example on AJAX with JSP in coming weekend. Please keep visit this blog for good tutorial on Java.
ReplyDeleteThanks,
Binod Suman
Hi Sir,
ReplyDeleteThis is Barani Kumar
I am new to ajax and I want web.xml file for ajax example programe
Please send to my id:vbaranikumar@gmail.com
Thanks
Barani Kumar
Hi Barani,
ReplyDeleteThere is nothing special in web.xml from Ajax point of view. Usually we used Ajax in java script to call server side function and get return data in JSP page. You can use normal web.xml in your application. Any way, I have sent web.xml to your mail id, what I have used for this example.
Keep watching my blog and you can put your suggestion and question in command box.
Thanks,
Binod Suman
http://binodsuman.blogspot.com
your code simply doesnt work ...
ReplyDeletei am making too many modifications to make ot run
please update it
so easy example. I was searching a good example of ajax with servlet. First time I got so stright forward example. A lot of ajax exmaple I got but with PHP only. Thanks a lot.
ReplyDeleteHi Abhinav,
ReplyDeleteFollow these step to run this example in Eclipse Europa editor. (Else you can use any other IDE also)
1. Open Eclipse
2. Give workspace name like C:\Ajax_workspace -> OK
3. File -> New -> Project -> web -> Dynamic web project -> next
4. Give Project name like blog_demo
5. Set any application server like apache tomcat, jboss, webshpere application server after click on Target runtime New button
6. After set up server click on Finish
7. Go to blog_demo -> webcontent -> right click -> New -> JSP -> Give file name ShowStudentInfo -> Finish
8. Delete every thing in ShowStudentInfo.jsp
9. Now copy from blog for ShowStudentInfo.jsp
10. Right click on blog_demo -> java Resource: src -> right click -> New -> Other -> Web -> Servlet
11. Put class name : StudentInfo -> Finish
12. Delete every thing from StudentInfo.java and copy code from blog and paste for StudentInfo.jav
13. Now start the sever
14. Right click on ShowStudentInfo.jsp -> Run as -> Run on server -> Finish
15. You will get GET STUDENT INFO page and put roll number 110, you will result.
If you get any error or exception, please let me know ........... :)
Really very easy step solution or tutorial. Thanks Binod. I followed the same steps and I see ajax is runing in my project.
ReplyDeleteHow to use ajax with JSP response. Please give one ajax example in which jsp sends some respons and parsing in jsp page.
ReplyDeleteRegards,
Jack
hey.. i'm having trouble with AJAX and FireFox... I'm frustrated abt this... pls help.. ASAP...
ReplyDeleteThis code runs fine on IE but not on Firefox... i think the problem is in the javascript function getElementsByTagName().... but i don't know how to solve it...
http://tinyurl.com/ajax-help
or
http://docs.google.com/View?id=dfv8mm9q_28ff5qrwht
regards,
Ashish
(Amrita School of engineering, Bangalore)
(IV year CSE)
hey... here is a ajax code that is working fine eith IE but not with firefox... i guess the prob is in the function getElementsByTagName()... but i'm not able to solve it...
ReplyDeletehttp://docs.google.com/View?id=dfv8mm9q_28ff5qrwht
or
http://tinyurl.com/ajax-help
pls help me... i'm frustrated... ASAP
Regards
Ashish
(Amrita School of Engineering, Bangalore)
(IV year CSE)
Hi Ashish, Thanks for pointing that my code does not work for Firefox. On your request I am posting one article that how to write ajax code for work for Firefox and IE. Please follow this below link
ReplyDeletehttp://binodsuman.blogspot.com/2009/06/ajax-program-for-firefox-ajax-does-not.html
Thanks,
Binod Suman
Hi,
ReplyDeleteCan you help me in building my application?
I have a requirement, how do we pass objects (say util class objects.. say HashMap) to jsp from servlet using AJAX. if possible then how de display the data in the jsp/html? please let me know ASAP.
Thanks,
Sree
Hi Binod,
ReplyDeletegreat tutorial. It is very useful. I wasn't able to see ajax works and now I see it.
I have two questions:
1) how can I invoke the servlet without useing the url: http://localhost:8080.....,
because I would like to use it also in different location and I'd like to have an independent url.
2) if I create the servlet in package (for example mypackage)
blog_demo -> java Resource -> mypackage
what I have to do to invoke the servlet from the javascript?
I'm very frustrating I'm not able to invoke a servlet from the xmlhttprequest.
Thank you for your help
Marco
Hi Mar,
ReplyDeleteIf your Servlet URL is working from internet explorer then it should also work with javascript. Suppose your URL is http://abc.com/myservlet/datainfo?roll=110, then you can use same in javascript using ajax program. Tell me if I am not clear.
Thanks,
Binod Suman
http://binodsuman.blogspot.com
Thanks for this example Binod.
ReplyDeleteDo you have any instructions on how to get it to work on netbeans? Preferably 6.7 (or the latest release).
When I run it on Netbeans, I get an error on the page - 'null' is null or not an object.
Thanks!
nice & easy example....thanks
ReplyDeleteHi dude, this post is awesome, i learnt ajax in just 1 day wid ur example described here.. thanks a lot dude ! Keep going ! Cheers !!! :-)
ReplyDeletehi
ReplyDeleteit was good tutorial to start with ajax
hi Binod,
ReplyDeleteI have tomcat project in eclipse. My project is written on JSP, Servlet. I need to use Ajax in one of my module. My requirement is on key press if I press Q, it hits server DB and get all names starting with Q. I used your servlet project, but its not working. DO I need any Jar file???
Please help me out with this.
Thanks,
Nithin Nayak
Hey,its a cool example of AJax..thank you very much..Its really helpful
ReplyDeletehow come this is a post request since you appending the parameters to url as get request.
ReplyDeletegood example
ReplyDeleteHi,
ReplyDeleteDoes anybody can provide code : how to populate values in drop down box with AJAX.
every time I run the example and put 110 in text field and submit it,,page got error and do nothing. whats the problem. I am using net bean 6.8.
ReplyDeleteif(request.readyState == 4){
var response = request.responseXML;
var students = response.getElementsByTagName("Student");
var student = students[0];
document.getElementById("NamelH1").innerHTML = student.getElementsByTagName("Name")[0].text;
document.getElementById("HostelH1").innerHTML = student.getElementsByTagName("Hostel")[0].text;
document.getElementById("ContactH1").innerHTML = student.getElementsByTagName("Contact")[0].text;
}else{
alert("Error");
}
hi could please help me with cross domain servlet call. I m trying to call a servlet which is on other domain. XHR doesnt work with cross domain...do u have any suggestions??? I have read many articles on proxy & cors......but no practical example...do u have any idea??
ReplyDeletehi.
ReplyDeleteNice tutorial. I need to make pagination in ajax servlet.I'm displaying one record from the table.If i click the next button it has to pick another record from the table. I'm able to fetch first record. But unable to get next one.. Could you please help me out.
hi.
ReplyDeleteNice tutorial. I need to make pagination in ajax servlet.I'm displaying one record from the table.If i click the next button it has to pick another record from the table. I'm able to fetch first record. But unable to get next one.. Could you please help me out.
Thanks for the good example. I am using Netbeans 7.0.1 and I created ShowStudentInfo.jsp and the StudentInfor.java as given in the Blog. When I run my JSP and put 110 nothing is happening and I am seeing that the code is not even reaching the Servlet. Does this example need any mapping to be done in the web.xml like we do with HTML Servlet interactions ? If so, at which jsp tag do we enter the info which maps to the web.xml which maps tpo the servlet ?
ReplyDeleteBrother, Thanks for the tutorial. G8 stuff
ReplyDeleteHi,
ReplyDeleteI am not getting any ajax response
var response = request.responseXML;
alert("response--> "+response);
no response.
but if I am using request.responseText ,I am getting the response.
request.onreadystatechange = function() { headerAlertCallback(request, 'headerAlertsSpan'); };
ReplyDeleterequest.open("GET","https://testorderseast.xxxx.com/portal/site/smo/headerAlertslink", true);
request.send(null);
If you look @ the testorderseast.xxx.com is our new domain we are trying to point our AJAX alerts Request.
So when we do that Alerts gets refresh from the Page.
So Now we are not able to point to a different specific URL because we use absoulte path and it worked. Since we are using the real specific URL it's giving all permission denied for security and stuff.
Can you please tell me instead of Servlet post how to make a Servlet get in this regard.
Hi Abhinav
ReplyDeleteI did everything as you said. But, no response when I enter the number
rajendrakumartvm@gmail.com
hi sir,
ReplyDeletenice tutorial. i learnt lot from this, but i dont have output. In the output
after i click the getname, there is no response, what can i do?
help me?
by
kavitha.n
thanks a lot....program worked well:(
ReplyDeleteHi,
ReplyDeleteI am also new to ajax. i want to display a set of data from database and display into jsp page. The data may contain 100 or 10000 records. how to display it in a table.
Thanks
hi sir,
ReplyDeletecan u help me in sending the best resource from net to learn html,xml,servlet,jsp,ajax.
thanQ
Hi, i am developing an application which has one drop down and when a value is selected, it results in another drop down, for this i am using ajax to call a servlet. But i'm getting error here.
ReplyDeletefunction callProcessArea() {
var xmlhttp;
var selectedvalue = document.getElementById("Areaid");
if (microsoft.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("Areaid").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", "/S1/src/..servletclasses/ProcessArea", true);
xmlhttp.send();
}
i am getting red marks in eclipse at following places:
document.getElementById, new XMLHttpRequest(), new ActiveXObject();xml.http.send(),xmlhttp.open(),
pleaseee some one help me with this.
changes in this line:
ReplyDeleterequest.open("POST",url,true);
here use method GET instead of POST so your modification is after this:
request.open("GET",url,true);
because of in servlet,doGet method is used.......simple..!!
changes in this line:
ReplyDeleterequest.open("POST",url,true);
here use method GET instead of POST so your modification is after this:
request.open("GET",url,true);
because of in servlet,doGet method is used.......simple..!!