AJAX with Servlets using JQuery and JSON

DOWNLOAD In my previous post , I explained about making AJAX calls to a servlet from a JSP page and updating a part of the JSP page w...



In my previous post, I explained about making AJAX calls to a servlet from a JSP page and updating a part of the JSP page with the response from the Servlet. That was a very simple example I provided in that post by returning a piece of text from the servlet to JSP to start with, and now in this post I am going to add something more to it by making the servlet return complex Java Objects such as lists, maps, etc. To do this, let us get introduced to JSON(Javascript Object Notation), in addition to JQuery and AJAX. JSON is derived from Javascript for representing simple data structures and associative arrays, called objects. Here in our scenario, we are going to use a JSON library in Servlet to convert Java objects (lists,maps,arrays.etc) to JSON strings that will be parsed by JQuery in the JSP page and will be displayed on the web page.


There are many JSON libraries available that can be used to pass AJAX updates between the server and the client. I am going to use google's gson library in this example. 

Now, let us create a simple JSP page with two drop down lists, one that contains values for countries and the other that is going to be populated with values for states based on the value of country selected in the first drop down list. Whenever the value is selected in the "country" drop down list, the "states" drop down list will be populated with corresponding state values based on the country selected. This has to be done without a page refresh, by making AJAX calls to the servlet on the drop down list change event.

Here are the steps to reproduce in Eclipse,

1. First of all create a "Dynamic Web Project" in Eclipse.
2. Create a new JSP page under "Webcontent" folder and copy paste the below code in it.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>AJAX calls to Servlet using JQuery and JSON</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
    $(document).ready(function() {
        $('#country').change(function(event) {  
        var $country=$("select#country").val();
           $.get('ActionServlet',{countryname:$country},function(responseJson) {   
            var $select = $('#states');                           
               $select.find('option').remove();                          
               $.each(responseJson, function(key, value) {               
                   $('<option>').val(key).text(value).appendTo($select);      
                    });
            });
        });
    });          
</script>
</head>
<body>
<h1>AJAX calls to Servlet using JQuery and JSON</h1>
Select Country:
<select id="country">
<option>Select Country</option>
<option value="India">India</option>
<option value="US">US</option>
</select>
<br/>
<br/>
Select State:
<select id="states">
<option>Select State</option>
</select>
</body>
</html>


3. Download google's GSON library from here and place it in your project's WEB-INF/lib folder.
4. Create a servlet in the name 'ActionServlet' (since I have used this name in the jquery code above') in the src directory. Copy and paste the below code in the doGet() method of the servlet and add the import statement in the header section of the servlet.

import com.google.gson.Gson;

protected void doGet(HttpServletRequest request,   HttpServletResponse response) throws ServletException, IOException {
 
  String country=request.getParameter("countryname");
  Map<String, String> ind = new LinkedHashMap<String, String>();
     ind.put("1", "New delhi");
     ind.put("2", "Tamil Nadu");
     ind.put("3", "Kerala");
     ind.put("4", "Andhra Pradesh");
     
     Map<String, String> us = new LinkedHashMap<String, String>();
     us.put("1", "Washington");
     us.put("2", "California");
     us.put("3", "Florida");
     us.put("4", "New York");
     String json = null ;
     if(country.equals("India")){
      json= new Gson().toJson(ind);   
     }
     else if(country.equals("US")){
      json=new Gson().toJson(us);  
     }
     response.setContentType("application/json");
     response.setCharacterEncoding("UTF-8");
     response.getWriter().write(json);       
 }

}


In the above code, we create two maps for two countries, and return the one based on the country parameter passed to the servlet in the AJAX call made by the JQuery's get() method. Here we convert the map objects to json strings in order to send the response back to the JSP page.

5. Make sure you have done servlet mapping properly in web.xml file. An example of this is given below,

<servlet>
    <servlet-name>ActionServlet</servlet-name>
    <servlet-class>ajaxdemo.ActionServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>ActionServlet</servlet-name>
    <url-pattern>/ActionServlet/*</url-pattern>
</servlet-mapping>


In the above code,'ajaxdemo' is the package name in which I have created the servlet. Replace it with your package structure to make the servlet work properly.



Thats it! You are now all set to run the project with Tomcat. When you run this project, the second drop down list will be populated automatically when you change the value in the first drop down list. 

Output Screenshots:

First drop down list changing,


On selecting 'India' in the first drop down list,


On selecting 'US' in the first drop down list,



Please leave your comments and queries about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts. 



Subscribe to GET LATEST ARTICLES!


Related

Jquery 7835410912476609284

Post a Comment

  1. Can we use ajax post here.. what are all the changes to be made for that?

    ReplyDelete
  2. @ameshlal: Yes. We can use. But GET method is generally used for receiving data from the server and post for updating date in the server. In this scenario it is most appropriate to use GET method.

    However if you want to use POST method for reasons like security, you just need to replace $.get method with a $.post in the above example.

    Even more simple example that alerts out the response data,

    $.post("ActionServlet", { name: "John", time: "2pm" },
    function(data) {
    alert("Data Loaded: " + data);
    });

    ReplyDelete
    Replies
    1. I tried your example. I can see the "responseJson" value in the index.jsp. But the values are not populated into states drop down box.

      Delete
    2. This example works fine for me. If the values are not populated in the second drop down box, you will have to debug your jquery response script. Please find the working source code for the above example in the below link. Hope this will help you compare and debug your application.

      https://www.dropbox.com/sh/arhvjju8pflnv2n/o6PIHy85GH/JSONAjax/

      Delete
  3. Its ok but i need ajax for more dropdown box ...How can i do it
    for ex cities in those states

    ReplyDelete
  4. Hello Priya,that was a very nice example.I'm trying to build a JSON object containing data that I retrieve from database in my servlet.So,how can I build such JSON object containing multiple arrays that themselves contains multiple key-value pairs.........
    Plz help me out with this one...........

    ReplyDelete
    Replies
    1. Hi,

      You have to create separate json object for each array of data you want to send from your servlet and then form a single json object that is an array of all the other json objects you created before. This single json object that contains an array of json objects has to be returned to the jsp. See Example below,

      Return Multiple JSON Objects from Servlets to JSP
      Server Side

      String json1 = new Gson().toJson(object1);
      String json2 = new Gson().toJson(object2);
      response.setContentType("application/json");
      String bothJson = "["+json1+","+json2+"]"; //Put both objects in an array of 2 elements
      response.getWriter().write(bothJson);

      Client side

      $.get("MyServlet", parameters, function (data){
      var data1=data[0], data2=data[1]; //We get both data1 and data2 from the array
      $("h3#name").text(data1["name"]);
      $("span#level").text(data1["level"]);
      $("span#college").text(data2["college"]);
      $("span#department").text(data2["department"]);
      });

      Delete
    2. Hi Priya,
      I'm trying to input student record (name,city,college)for 3 students using a loop.I've used JSONObject to store each detail.Then I've added that JSONObject to a JSONArray then I've added that array obj to JSONObject.but its displaying the last set of values I enter for all 3 records....

      Code snippet:

      for(i=0;i<3;i++)
      {
      System.out.println("Enter name");
      name = input.readLine();
      System.out.println("Enter city");
      city = input.readLine();
      System.out.println("Enter college");
      college = input.readLine();

      detail.put("name",name);
      detail.put("city",city);
      detail.put("college",college);

      arr.put(i,detail);
      obj.put("student",arr);
      }

      String output = gson_obj.toJson(obj);
      System.out.println("Output: "+output);

      Input:{1,2,3} {4,5,6} {7,8,9}(Suppose)

      Output: {"myHashMap":{"student":{"myArrayList":[{"myHashMap":{"name":"7","college":"9","city":"8"}},{"myHashMap":{"name":"7","college":"9","city":"8"}},{"myHashMap":{"name":"7","college":"9","city":"8"}}]}}}

      Can u plz tell me where am I going wrong..I'm actually trying to build a JSON obj after retrieving data from database. of the form.........
      {students: [student{name,city,college},student{name,city,college},student{name,city,college}]}

      Delete
  5. hai i got some problem ,,,,,
    i rerieve the values but how to display for the textbox ...
    pls help me

    ReplyDelete
  6. Hi Priya,
    Thanks for this example. It is very helpful to me. Do you have same example with mysql database? Would you please upload it

    ReplyDelete
    Replies
    1. Hi Sumit,

      Welcome! Check out my latest post,

      AJAX Fetch Data from Database in JSP and Servlet with JSONArray

      Hope this helps too!

      Thanks,
      Priya

      Delete
    2. Hi Priya,

      Thanks a lot, your latest post AJAX Fetch Data from Database in JSP and Servlet with JSONArray helped me a lot.

      Thanks,
      Sumit

      Delete
  7. hi thx priya, this article help me a lot....

    ReplyDelete
  8. Hi priya ,

    Nice examples,
    I have one question and I am not able to get solution on it
    Here we selecting one country say india and we are getting list of states in india
    now what should I do if I select both INDIA and US together then we should get all states of India and us within that drop down . How to do this.

    I am able to select multiple countries using (multiple="multiple" ) in JSP but not able to get states so how to do this ... Can you pleaase help me on this

    ReplyDelete
    Replies
    1. Hi Dhaval,

      If you want to enable users to select multiple options, then you have to make ajax calls to servlet whenever an option is selected and deselected. Make sure servlet contains appropriate code to handle each option.

      Check this out for a simple example on how to handle multiple select option in jquery,

      http://api.jquery.com/change/

      Hope this helps!

      Thanks,
      Priya

      Delete
  9. Hi Priya,
    maybe your code may be missing of a starting import like:
    import java.util.*;

    Otherwise LinkedHashMap is not recognized

    ReplyDelete
  10. Hi Priya, can you help me with my question that I post in stackoverflow
    http://stackoverflow.com/questions/18527323/ask-different-response-from-servlet-use-ajax-and-jsp

    I've got trouble on the servlet coz I can't access the different block "if-else condition". Can you help me?

    Thanks Priya.

    ReplyDelete
  11. Hi priya,
    this one is good example, and i want to get JsonArray from server which contains no.of states, and after i want to populate into drop down box(into select tag), without iteration(like without using $each). is there any scenario, if there plz tell me how to do.

    Thank u.

    ReplyDelete
  12. and one more thing it is working with Gson object, what about JSONObject,how to use JsonObect to send data to client

    ReplyDelete
  13. thanks a lot, it was high time i updated from using js based ajax calls to jQuery based ones...

    ReplyDelete
  14. thank you for this helpful tutorials. I am trying to send two or more one dimensional arrays from servlet to a JSP, I tried
    json= new Gson().toJson("["+a1+","+a2+"]"); any help in this regard are highly appreciated

    ReplyDelete
  15. Well, I just posted about your other jQuery/AJAX example and how quick and easy it was to set up and understand, and then I find this one.

    Another simple easy to understand and working example of jQuery/AJAX/JSON...
    Although this took about 5 minutes to get working :-)

    Thank you again

    ReplyDelete
    Replies
    1. Thank you so much for your comment. Keep yourself subscribed to ProgrammingFree via email or social networks for more such useful articles.

      Delete
  16. Hi many thanks for the example has helped me a lot.

    I have a question, I have a arraylist in a class that brings me the names of the State but as I can not pass it to map the servlet

    example.

    servlet.

    this is how I bring the arraylist to servlet

           Consultations Consultations userLis = new ();
              In = userLis.Consultapais ArrayList ();
             
              Map Of String ind = new LinkedHashMap ();
                
      for (Country country: in) {
             ind.put (pais.getNombre (), country);
              
              }

    and run it in the combobox

    I above shows this.

    [object Object]

    I would greatly appreciate if you could help.

    Thank you. :rapt: :rapt:

    ReplyDelete
  17. Thanks priya its a very useful tutorial. But i have an problem that i want to populate data from databse onBlur event of a text field. i tried it for select than its worked fine but when i tried with textfield then i faced a problem that how can we pass textfield value to servlet using json.
    plese help.

    ReplyDelete
  18. Can you post a similar tutorial where the drop down list is populated dynamically from servlets JSON. A three tier tutorial will be a great tutorial I think.

    Thanks

    ReplyDelete
  19. can u add one more dependent dropdown list like distict there

    ReplyDelete
  20. I am having issues running this code that u gave in this post..
    I think there is an issue with GSON lib .. from the link that u gave i got 3 executable jar files and placed them WEB-INF/lib but when i run this code nothing happens :disappointed: ie when i click on US/INDIA ther is nothing in the states .. plz help

    ReplyDelete
  21. Hi Priya,
    Thanks for jTable example. Helped me a lot....

    ReplyDelete
  22. Thanks for the example...
    If i need to pass the two dropdown boxes values when i press submit button. Then how can i get the value of second dropdownbox? there is no "value" attribute in second dropdown tag option

    ReplyDelete
  23. This comment has been removed by the author.

    ReplyDelete
  24. I got this error Uncaught TypeError: $.get is not a function
    How can I solve this? I've tried importing the complete jquery lib and changing $ to jquery...it doesnt work..

    ReplyDelete
  25. please can you explain the jquery code populated statenames

    ReplyDelete
  26. bro just use jquery having ajax also.
    there is a cdn of jquery which supports ajax.

    ReplyDelete
  27. Nice post. Thanks for sharing! I want people to know just how good this information is in your article. It’s interesting content and Great work.
    Thanks & Regards,
    VRIT Professionals,
    No.1 Leading Web Designing Training Institute In Chennai.

    ReplyDelete
  28. This is really impressive post, I am inspired with your post, do post more blogs like this, I am waiting for your blogs.
    R Training Institute in Chennai | R Programming Training in Chennai

    ReplyDelete
  29. Wonderful post. Keep working and Share these types of blogs. Home elevators | hydraulic elevators

    ReplyDelete
  30. Hi,
    Thanks for sharing, it was informative. We play a small role in upskilling people providing the latest tech courses. Join us to learn and adapt new techniques on DEVOPS

    ReplyDelete
  31. Good Work, i like the way you describe this topic, keep going. i would like to share some useful security links here please go through.share more related content..
    Ai & Artificial Intelligence Course in Chennai
    PHP Training in Chennai
    Ethical Hacking Course in Chennai Blue Prism Training in Chennai
    UiPath Training in Chennai

    ReplyDelete
  32. https://ngdeveloper.com/json-servlet-ajax-call/

    ReplyDelete
  33. Asp .Net Development Services has the propelled aspect of Micro's.Net structure and it is viewed as the best application system for building dynamic asp.net web development services and Custom application development company. Subsequently the cutting edge asp.net advancement organizations that have dynamic website specialists and online application engineers profoundly depend on this. The accompanying focuses made ASP .Net a default decision for everybody. Asp .Net Development Company (articulated speck net) is a system that gives a programming rules that can be utilized to build up a wide scope of uses – from web to portable to Windows-based applications. The .NET system can work with a few programming dialects, for example, C#, VB.NET, C++ and F#. At Grand Circus, we use C#.

    ReplyDelete
  34. This comment has been removed by the author.

    ReplyDelete
  35. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
    Data Science Course Hyderabad

    ReplyDelete
  36. Thanks for giving great kind of information. So useful and practical for me. Thanks for your excellent blog, nice work keep it up thanks for sharing the knowledge.

    DevOps Training in Chennai

    DevOps Course in Chennai



    ReplyDelete
  37. I've seen articles on the same subject many times, but your writing is the simplest and clearest of them. I will refer to 메이저놀이터

    ReplyDelete
  38. Hi ! I specialize in writing on these topics. My blog also has these types of articles and forums. Please visit once. 메이저놀이터

    ReplyDelete
  39. I need you to thank for your season of this awesome 먹튀검증!!! I definately appreciate each and every piece of it and I have you bookmarked to look at new stuff of your blog an absolute necessity read blog!!!!

    ReplyDelete
  40. I am overwhelmed by your post with such a nice topic. Usually I visit your 메이저토토사이트 and get updated through the information you include but today’s blog would be the most appreciable. Well done!

    ReplyDelete
  41. Hello, I'm happy to see some great articles on your site. Would you like to come to my site later? My site also has posts, comments and communities similar to yours. Please visit and take a look 우리카지노

    ReplyDelete
  42. The article composing business is going extraordinary for me at this moment, and the vast majority of my prosperity is because of the substance that you post here. I utilize your substance to compose my articles, and the substance makes my great article incredible. 바카라사이트

    ReplyDelete
  43. I'm writing on this topic these days, , but I have stopped writing because there is no reference material. Then I accidentally found your article. I can refer to a variety of materials, so I think the work I was preparing will work! Thank you for your efforts. 토토커뮤니티

    ReplyDelete
  44. I'm writing on this topic these days, 먹튀사이트, but I have stopped writing because there is no reference material. Then I accidentally found your article. I can refer to a variety of materials, so I think the work I was preparing will work! Thank you for your efforts.

    ReplyDelete
  45. It's really great. Thank you for providing a quality article. There is something you might be interested in. Do you know 메이저토토 ?

    ReplyDelete
  46. Thanks for some other excellent article. The place else may anybody get that type of info in such an ideal means of writing? I have a presentation next week, and I’m on the search for such information. 먹튀검증커뮤니티

    ReplyDelete
  47. I’m very pleased to discover this site. I want to to thank you for ones time for this particularly wonderful read!! I definitely savored every part of it and i also have you saved as a favorite to see new information on your blog. 메이저토토사이트

    ReplyDelete
  48. I've been troubled for several days with this topic. Kèo nhà cái, But by chance looking at your post solved my problem! I will leave my blog, so when would you like to visit it?

    ReplyDelete
  49. What a post I've been looking for! I'm very happy to finally read this post. 토토커뮤니티 Thank you very much. Can I refer to your post on my website? Your post touched me a lot and helped me a lot. If you have any questions, please visit my site and read what kind of posts I am posting. I am sure it will be interesting.

    ReplyDelete
  50. Hi, after reading this remarkable piece of writing i am as well happy to share my experience here with friends.

    Also visit my webpage - 부산달리기


    (jk)

    ReplyDelete
  51. First of all, thank you for your post. Your posts are neatly organized with the information I want, so there are plenty of resources to reference. I bookmark this site and will find your posts frequently in the future. Thanks again ^^ 먹튀커뮤니티

    ReplyDelete
  52. Why users still use to read news papers when in this technological
    globe all is available on net? 바카라사이트

    ReplyDelete
  53. Thank you for the good writeup. It in fact was a amusement account it. Look advanced to more added agreeable from you! 사설토토

    ReplyDelete
  54. Excellent Blog! I would like to thank you for sharing this content with us! This is a very good read. In fact, most posts on your blog are great reads. You've clearly put a lot of effort into this and I really appreciate it all. Thanks for sharing.
    Data Science Training in Hyderabad
    Data Science Course in Hyderabad

    ReplyDelete
  55. I want to encourage you to continue your great posts. You have some good points here. Thanks for sharing. Check My NECO Result 2020

    ReplyDelete
  56. That's a really impressive new idea! 메이저토토사이트추천 It touched me a lot. I would love to hear your opinion on my site. Please come to the site I run once and leave a comment. Thank you.


    ReplyDelete
  57. You are providing a post that is very useful for developing my knowledge and I learn more info from your blog.
    Pega Online Course
    Azure online Training

    ReplyDelete
  58. When I read an article on this topic, 먹튀검증커뮤니티 the first thought was profound and difficult, and I wondered if others could understand.. My site has a discussion board for articles and photos similar to this topic. Could you please visit me when you have time to discuss this topic?

    ReplyDelete
  59. It has fully emerged to crown Singapore's southern shores and undoubtedly placed her on the global map of residential landmarks. I still scored the more points than I ever have in a season for GS. I think you would be hard pressed to find somebody with the same consistency I have had over the years so I am happy with that. 메이저토토사이트

    ReplyDelete
  60. This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value. Im glad to have found this post as its such an interesting one! I am always on the lookout for quality posts and articles so i suppose im lucky to have found this! I hope you will be adding more in the future. 토토사이트추천

    ReplyDelete
  61. Exactly how can you have such abilities? I can not evaluate your abilities yet, yet your writing is fantastic. I thought of my instructions once again. I desire a professional like you to review my writing and also court my writing since I'm truly interested concerning my abilities. 실시간 바카라사이트

    ReplyDelete
  62. I really like it when individuals come together and share opinions.
    Great blog, stick with it!Click Me Here오피월드


    3CHERE

    ReplyDelete
  63. We are looking for a lot of data on this item. In the meantime, this is the perfect article I was looking for . Please post a lot about items related to 메이저놀이터추천 !!! I am waiting for your article. And when you are having difficulty writing articles, I think you can get a lot of help by visiting my .

    ReplyDelete
  64. Thanks for sharing this valuable information. It will be useful for knowledge seekers.
    JMeter Training in Chennai
    JMeter Online Training

    ReplyDelete
  65. What a post I've been looking for! I'm very happy to finally read this post. 먹튀검증 Thank you very much. Can I refer to your post on my website? Your post touched me a lot and helped me a lot. If you have any questions, please visit my site and read what kind of posts I am posting. I am sure it will be interesting.

    ReplyDelete
  66. We are looking for a lot of data on this item. In the meantime, this is the perfect article I was looking for . Please post a lot about items related to 바카라사이트!!! I am waiting for your article. And when you are having difficulty writing articles, I think you can get a lot of help by visiting my .

    ReplyDelete
  67. When I read your article on this topic, the first thought seems profound and difficult. There is also a bulletin board for discussion of articles and photos similar to this topic on my site, but I would like to visit once when I have time to discuss this topic. sòng bạc


    ReplyDelete
  68. Your ideas inspired me very much. 메이저토토사이트모음 It's amazing. I want to learn your writing skills. In fact, I also have a website. If you are okay, please visit once and leave your opinion. Thank you.

    ReplyDelete
  69. I searched a lot on this topic and finally found it. I read your post and was very impressed. We visit this site frequently to appreciate your comments. keo nhacai

    ReplyDelete
  70. 👻

    토토사이트
    먹튀검증
    토토사이트추천


    Everyone loves it when people come together
    and share opinions. Great site, continue the good work!


    ReplyDelete
  71. 토토사이트
    안전놀이터


    I really love your site.. Pleasant colors & theme.
    Did you make this web site yourself? Please reply back
    as I'm planning to create my own personal blog and would like to know where you got this from or what the theme is named.
    Thank you!

    ReplyDelete
  72. This comment has been removed by the author.

    ReplyDelete
  73. We have all lived in the hype around cybersecurity and how if we don't pay attention, it can become our nightmare, one where even the best corporate securities and government will not be able to intervene. Cloud Security

    ReplyDelete
  74. Excellent blog!!! I really enjoy to read your post and thanks for sharing!
    Uncontested Divorce in VA
    VA Uncontested Divorce

    ReplyDelete
  75. thank for this article ,currently i am learning JSON and your blog helping me.

    ReplyDelete
  76. This blog by you is an absolute gem of information for those who are new to the concept of Spring MVC and Restful Web Services. You have done an excellent job in providing a comprehensive and detailed explanation of the entire process. Your use of diagrams, examples and illustrations to help explain the process has been extremely helpful and have gone a long way in making it easier to understand the concepts. I really appreciate your effort and dedication in creating this blog, as it has definitely been a great help in my learning. Thank you for your hard work. Best Technical Writing Courses in India

    ReplyDelete

emo-but-icon

SUBSCRIBE


item