Saturday, May 9, 2009

Get start with Ajax, Ajax simple example with Servlet, Ajax programming with Servlet

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.

65 comments:

  1. First of all thanks for easy example. Could you please provide any easy example for Ajax with JSP. Thanks.

    ReplyDelete
    Replies
    1. http://www.programming-free.com/2012/09/ajax-with-servlets-using-jquery-and-json.html

      Delete
  2. Thanks 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.

    Thanks,
    Binod Suman

    ReplyDelete
  3. Hi Sir,
    This 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

    ReplyDelete
  4. Hi Barani,
    There 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

    ReplyDelete
  5. your code simply doesnt work ...
    i am making too many modifications to make ot run
    please update it

    ReplyDelete
  6. 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.

    ReplyDelete
  7. Hi Abhinav,
    Follow 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 ........... :)

    ReplyDelete
    Replies
    1. HTTP Status 404 - /blog_demo/ShowStudentInfo.jsp

      --------------------------------------------------------------------------------

      type Status report

      message /blog_demo/ShowStudentInfo.jsp

      description The requested resource (/blog_demo/ShowStudentInfo.jsp) is not available.


      --------------------------------------------------------------------------------

      Apache Tomcat/6.0.35

      Delete
    2. hello binod...
      I am not able to click on that button GET NAME

      Delete
    3. helo binod..
      I am not able to click n the GET Name BUTTON
      PLZ HELP ME

      Delete
  8. Really very easy step solution or tutorial. Thanks Binod. I followed the same steps and I see ajax is runing in my project.

    ReplyDelete
  9. How to use ajax with JSP response. Please give one ajax example in which jsp sends some respons and parsing in jsp page.

    Regards,

    Jack

    ReplyDelete
  10. hey.. i'm having trouble with AJAX and FireFox... I'm frustrated abt this... pls help.. ASAP...

    This 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)

    ReplyDelete
  11. 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...

    http://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)

    ReplyDelete
  12. 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

    http://binodsuman.blogspot.com/2009/06/ajax-program-for-firefox-ajax-does-not.html

    Thanks,

    Binod Suman

    ReplyDelete
  13. Hi,

    Can 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

    ReplyDelete
  14. Hi Binod,
    great 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

    ReplyDelete
  15. Hi Mar,
    If 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

    ReplyDelete
  16. Thanks for this example Binod.

    Do 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!

    ReplyDelete
  17. nice & easy example....thanks

    ReplyDelete
  18. Hi dude, this post is awesome, i learnt ajax in just 1 day wid ur example described here.. thanks a lot dude ! Keep going ! Cheers !!! :-)

    ReplyDelete
  19. hi
    it was good tutorial to start with ajax

    ReplyDelete
  20. hi Binod,
    I 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

    ReplyDelete
  21. Hey,its a cool example of AJax..thank you very much..Its really helpful

    ReplyDelete
  22. how come this is a post request since you appending the parameters to url as get request.

    ReplyDelete
  23. Hi,
    Does anybody can provide code : how to populate values in drop down box with AJAX.

    ReplyDelete
  24. 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.
    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;
    }else{
    alert("Error");
    }

    ReplyDelete
  25. 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??

    ReplyDelete
  26. hi.
    Nice 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.

    ReplyDelete
  27. hi.
    Nice 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.

    ReplyDelete
  28. 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 ?

    ReplyDelete
  29. Brother, Thanks for the tutorial. G8 stuff

    ReplyDelete
  30. Hi,
    I 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.

    ReplyDelete
  31. request.onreadystatechange = function() { headerAlertCallback(request, 'headerAlertsSpan'); };
    request.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.

    ReplyDelete
  32. Hi Abhinav
    I did everything as you said. But, no response when I enter the number
    rajendrakumartvm@gmail.com

    ReplyDelete
  33. hi sir,
    nice 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

    ReplyDelete
  34. thanks a lot....program worked well:(

    ReplyDelete
  35. Hi,

    I 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

    ReplyDelete
  36. hey Binod can u pls help....my code is not running...
    wat i hav done,i have copied *.jsp and *.java file as u have given....i have changed url field of *.jsp file....i am not getting o/p after enter roll no-110 or any other.pls help

    ReplyDelete
  37. pls help Binod...
    i have copied *.jsp & *.java file as it is,change i have done is in url field of *.jsp
    im entering roll no-110,still not getting any o/p...
    pls help

    ReplyDelete
  38. I have replaced the javascript in ShowStudentInfo.jsp to the following and it works for me in Firefox 14 & IE 9:

    var request;
    function getName() {
    var roll = document.getElementById("roll").value;
    var url = "StudentInfo?roll=" + roll;

    if (window.XMLHttpRequest)
    {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    request = new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
    // code for IE6, IE5
    request = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else
    {
    alert("Your browser does not support XMLHTTP!");
    }

    request.onreadystatechange = showResult;
    request.open("POST", url, true);
    request.send();
    }
    function showResult() {
    if (request.readyState == 4) {
    var response = request.responseXML;
    document.getElementById("NamelH1").innerHTML = response
    .getElementsByTagName("Name")[0].firstChild.nodeValue;
    document.getElementById("HostelH1").innerHTML = response
    .getElementsByTagName("Hostel")[0].firstChild.nodeValue;
    document.getElementById("ContactH1").innerHTML = response
    .getElementsByTagName("Contact")[0].firstChild.nodeValue;
    }
    }

    ReplyDelete
  39. hi sir,
    can u help me in sending the best resource from net to learn html,xml,servlet,jsp,ajax.
    thanQ

    ReplyDelete
  40. Hello Binod.....
    there is no result after clicking on get name button
    plx help me

    ReplyDelete
  41. Thank sir i got very much info from blog example....thank x a lot...

    ReplyDelete
  42. 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.

    function 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.

    ReplyDelete
  43. changes in this line:
    request.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..!!

    ReplyDelete
  44. changes in this line:
    request.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..!!

    ReplyDelete
  45. Hi Sir,

    Iam new to web applications.Can u kindly send me the Web.xml for this application to mandadi.praneethkumar@gmail.com

    ReplyDelete
  46. Hi Sir,

    Can u kindly send me the web.xml file to mandadi.praneethkumar@gmail.com

    ReplyDelete
  47. Great Tutorial..., we don't know why google doesn't search this type of blogs.

    ReplyDelete
  48. Great Tutorial...
    Why google doesn't search this type of blogs

    ReplyDelete
  49. Hi sir,
    i have an requirement that table content should be changed without reloading the page can you provide an example where we can access data from data base from servlet and display it on jsp page or HTML page without reloading the current HTML or jsp page

    ReplyDelete
  50. If the above does not work , change the getName() as follow: Note: change the servlet url:


    function getName(){
    var roll = document.getElementById("roll").value;
    var url = "http://localhost:8080//YourServlet?roll="+roll;
    if(window.ActiveXObject){
    request = new ActiveXObject("Microsoft.XMLHTTP");
    } else if(window.XMLHttpRequest) {
    request = new XMLHttpRequest();
    }
    request.onreadystatechange = function (){
    if (request.readyState == 4 ){
    var response = request.responseXML;
    var students = response.getElementsByTagName("Student");
    for (i=0;i<students.length;i++){
    xa=students[i].getElementsByTagName("Name");
    document.getElementById("NamelH1").innerHTML = xa[0].firstChild.nodeValue;
    xb=students[i].getElementsByTagName("Hostel");
    document.getElementById("Hostel H1").innerHTML = xb[0].firstChild.nodeValue;
    xc=students[i].getElementsByTagName("Contact");
    document.getElementById("Contact H1").innerHTML = xc[0].firstChild.nodeValue;
    }
    }
    } ;
    request.open("POST",url,true);
    request.send();
    }

    Cheers
    Anjan

    ReplyDelete
  51. Hi,
    I have a requirement..i need to invalidate session once the browser window is closed.How can i do it using ajax.

    Thanks

    ReplyDelete
  52. good work :) helped me

    ReplyDelete
  53. I have picked up a lot of handy things out of this amazing blog.

    ReplyDelete
  54. above code works...but values are not getting....undefined values are shown

    ReplyDelete
  55. Thanks for sharing such a great information..Its really nice and informative..

    java training institute

    ReplyDelete

You can put your comments here (Either feedback or your Question related to blog)