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

https://www.programming-free.com/2012/09/ajax-with-servlets-using-jquery-and-json.html
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.
good example
ReplyDeleteCan we use ajax post here.. what are all the changes to be made for that?
ReplyDelete@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.
ReplyDeleteHowever 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);
});
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.
DeleteThis 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.
Deletehttps://www.dropbox.com/sh/arhvjju8pflnv2n/o6PIHy85GH/JSONAjax/
Its ok but i need ajax for more dropdown box ...How can i do it
ReplyDeletefor ex cities in those states
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.........
ReplyDeletePlz help me out with this one...........
Hi,
DeleteYou 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"]);
});
Hi Priya,
DeleteI'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}]}
Hi,
DeleteCheck this out,
AJAX Fetch Data from Database in JSP and Servlet with JSONArray
Thanks,
Priya
hai i got some problem ,,,,,
ReplyDeletei rerieve the values but how to display for the textbox ...
pls help me
Hi Priya,
ReplyDeleteThanks for this example. It is very helpful to me. Do you have same example with mysql database? Would you please upload it
Hi Sumit,
DeleteWelcome! Check out my latest post,
AJAX Fetch Data from Database in JSP and Servlet with JSONArray
Hope this helps too!
Thanks,
Priya
Hi Priya,
DeleteThanks a lot, your latest post AJAX Fetch Data from Database in JSP and Servlet with JSONArray helped me a lot.
Thanks,
Sumit
Most Welcome!
Deletehi thx priya, this article help me a lot....
ReplyDeleteMost Welcome!
DeleteHi priya ,
ReplyDeleteNice 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
Hi Dhaval,
DeleteIf 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
Hi Priya,
ReplyDeletemaybe your code may be missing of a starting import like:
import java.util.*;
Otherwise LinkedHashMap is not recognized
Hi Priya, can you help me with my question that I post in stackoverflow
ReplyDeletehttp://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.
Hi priya,
ReplyDeletethis 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.
and one more thing it is working with Gson object, what about JSONObject,how to use JsonObect to send data to client
ReplyDeletethanks a lot, it was high time i updated from using js based ajax calls to jQuery based ones...
ReplyDeleteGlad that you made it now :like:
Deletethank you for this helpful tutorials. I am trying to send two or more one dimensional arrays from servlet to a JSP, I tried
ReplyDeletejson= new Gson().toJson("["+a1+","+a2+"]"); any help in this regard are highly appreciated
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.
ReplyDeleteAnother simple easy to understand and working example of jQuery/AJAX/JSON...
Although this took about 5 minutes to get working :-)
Thank you again
Thank you so much for your comment. Keep yourself subscribed to ProgrammingFree via email or social networks for more such useful articles.
DeleteHi many thanks for the example has helped me a lot.
ReplyDeleteI 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:
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.
ReplyDeleteplese help.
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.
ReplyDeleteThanks
can u add one more dependent dropdown list like distict there
ReplyDeleteI am having issues running this code that u gave in this post..
ReplyDeleteI 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
Hi Priya,
ReplyDeleteThanks for jTable example. Helped me a lot....
Thanks for the example...
ReplyDeleteIf 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
How to do this in struts2
ReplyDeleteThis comment has been removed by the author.
ReplyDeletefuck you, idiot
ReplyDeleteI got this error Uncaught TypeError: $.get is not a function
ReplyDeleteHow can I solve this? I've tried importing the complete jquery lib and changing $ to jquery...it doesnt work..
please can you explain the jquery code populated statenames
ReplyDeletebro just use jquery having ajax also.
ReplyDeletethere is a cdn of jquery which supports ajax.
Informative post.
ReplyDeleteR Programming Training in Chennai
Very good to read this post
ReplyDeleteR programming training institute in chennai
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.
ReplyDeleteThanks & Regards,
VRIT Professionals,
No.1 Leading Web Designing Training Institute In Chennai.
Really awesome blog. Your blog is really useful for me
ReplyDeleter programming training in chennai | r training in chennai
r language training in chennai | r programming training institute in chennai
Best r training in chennai
Very nice blog, Thank you for providing good information.
ReplyDeleteAviation Academy in Chennai
Air hostess training in Chennai
Airport management courses in Chennai
Ground staff training in Chennai
This is really impressive post, I am inspired with your post, do post more blogs like this, I am waiting for your blogs.
ReplyDeleteR Training Institute in Chennai | R Programming Training in Chennai
Wonderful post. Keep working and Share these types of blogs. Home elevators | hydraulic elevators
ReplyDeletevery informative keepsharing
ReplyDeletefreeinplanttrainingcourseforECEstudents
internship
internship-for-aeronautical-engineering-students-in-india
internship-for-cse-3rd-year-students
freeinplanttrainingcourseforMECHANICALstudents
internship-in-chennai-for-ece
inplant-training-for-civil
internship-at-bsnl
internship-for-2nd-year-ece-students
internship-for-aeronautical-students-in-chennai
nice information....
ReplyDeleteInplant Training in Chennai
Iot Internship
Internship in Chennai for CSE
Internship in Chennai
Python Internship in Chennai
Implant Training in Chennai
Android Training in Chennai
R Programming Training in Chennai
Python Internship
Internship in chennai for EEE
GREAT...
ReplyDeleteCrome://Flags
Python Programming Questions and Answers PDF
Qdxm Sfyn Uioz
How To Hack Whatsapp Account Ethical Hacking
Power Bi Resume
Whatsapp Unblock Software
Tp Link Password Hack
The Simple Interest Earned On a Certain Amount Is Double
A Certain Sum Amounts To RS. 7000 in 2 years and to RS. 8000 in 3 Years. Find The Sum.
Zensoft Aptitude Questions
informative post...
ReplyDeletePython Internship
Dotnet Internship
Java Internship
Web Design Internship
Php Internship
Android Internship
Big Data Internship
Cloud Internship
Hacking Internship
Robotics Internship
TECHNICAL KNOWLEGE DEVELOPMENT...
ReplyDeleteOracle Internship
R Programming Internship
CCNA Internship
Networking Internship
Artificial Intelligence Internship
Machine Learning Internship
Blockchain Internship
Sql Server Internship
Iot Internship
Data Science Internship
GOOD
ReplyDeleteFree Internship for cse students in Chennai
R Programming Internship
Hadoop Training in Chennai
Free Internship Training in Chennai
Robotics Training chennai
Summer Internship For BSC students
Internships in Chennai for CSE
CCNA Institute in Chennai
Data Science Internship in Chennai
Aeronautical Engineering Internship
GOOD WORK
ReplyDeleteGeteventlisteners javascript
Karl fischer titration interview questions
How to hack tp link router
T system aptitude questions
Resume for bca final year student
Test case for railway reservation system
T systems pune placement papers
Infrrd bangalore interview questions
Max number in javascript
Paypal integration in php step by step pdf
technical information....
ReplyDeleteSelenium Testing Internship
Linux Internship
C Internship
CPP Internship
Embedded System Internship
Matlab Internship
nice....
ReplyDeleteFREE Internship in Nagpur For Computer Engineering Students
Internship For MCA Students
Final Year Projects For Information Technology
Web Design Class
Mechanical Engineering Internship Certificate
Inplant Training For Mechanical Engineering Students
Inplant Training Certificate
Ethical Hacking Course in Chennai
Winter Internship For ECE Students
Internships For ECE Students in Bangalore
great
ReplyDeleteHow To Hack On Crosh
Request Letter For Air Ticket Booking To HR
Zeus Learning Aptitude Paper For Software Developer
Cimpress Interview Questions
VCB Rating
Appreciation Letter To Vendor
JS MAX Safe Integer
Why Do You Consider Yourself Suitable For The Position
How To Hack Android Phone From PC
About Bangalore Traffic Essay
GOOD
ReplyDeletehacking course
internship for it students
civil engineering internship report pdf india
ccna course chennai
internship report for civil engineering students in india
internships in hyderabad for cse students 2018
kashi infotech
cse internships in hyderabad
inplant training for diploma students
internship in hyderabad for cse students
GOOD
ReplyDeletenodejs while loop
icici bank po interview questions and answers pdf
craterzone aptitude test
zensoft recruitment process
java developer resume 1 years experience
python developer resume pdf
infrrd private limited interview questions
js int max value
delete * from table oracle
t systems pune aptitude questions
nice
ReplyDeleteInternship For Aerospace Engineering
Mechanical Engineering Internships in Chennai
Robotics Courses
Kaashiv
Training Letter Format For Mechanical Engineer
Internship For BCA Student
Fake Internship Certificate
MBA Internship
Free Internship For CSE Students in Chennai
Oracle Internship 2020
ngreat information
ReplyDeleteJavascript Maximum Integer
INT MAX Javascript
Acceptance is to an Offer What a Lighted Match is to a Train of Gunpowder
Who Can Issue Character Certificate
Technical Support Resume DOC
PHP Developer Resume For 3 Year Experience
Wapda Interview Questions
Power BI Resume Download
a Dishonest Dealer Professes to Sell His Goods at a Profit of 20
Failed to Find 'Android_Home' Environment Variable. TRY Setting it Manually
good
ReplyDeleteiot training in coimbatore
summer training for 3rd year electronics and communication engineering students
goa current affairs 2019
project for information technology students
online internship for bca students
winter training for mechanical engineering students
ccna training
industrial training report for electronics and communication pdf
matlab courses in chennai
bba internship project
good
ReplyDeleteResume Format For Bca Freshers
British Airways Interview Questions And Answers Pdf
Asus Tf101 Android 8
Crome://Flags/
T Systems Aptitude Test
Python Resume Ror 2 Years Experience
Ajax Redirect To Another Page With Post Data
Paramatrix Technologies Aptitude Questions And Answers
Adder Subtractor Comparator Using Ic 741 Op-Amp Theory
How To Hack Wifi With Ubuntu