Ajax json jquery Post example - Java @ Desk

Thursday, August 14, 2014

Ajax json jquery Post example

Ajax json jquery Post example

Ajax is used to update the parts of the web page with out reloading the entire page.

JSON is used to store and exchange the data between client and server.

Enums is used to store the data means a list of named constants.

In this example, Data will be loaded into drop down list based on the selected option(country) using Jquery and the above mentioned technologies.

Unlike JSP's , we can make use of HTML itself by using JSON concept for data exchange between client and server.

In this example, Dynamic data loading is shown by using drop down list, Code has flexibility to extend to other elements of a web page. Whenever Country option has selected OnChange event will be triggered and it in turn calls the specified function, In this example it was callRegCountry(), which has Ajax call (Asynchronous JavaScript and XML.) nothing but a replacement of Form submit in a better way.

Ajax and its terms:

type : Type of request eg: get, post
url : The URL to which the request has to sent,Typically Servlet or JSP.
data : An object or string that is sent to the server with the request.
Success : A callback function that is executed if the request succeeds.
Error : function called When request completes with an error

HTML Code:

<!DOCTYPE html>
<meta charset="ISO-8859-1">
<title>AJAX-JSON example</title>
<meta name="description"
 content="Dynamic Loading of data by Ajax via JSON and enums">
<meta name="author" content="sekhar">

<!-- jquery.js is loaded through Google CDN-->

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<!-- JSON2.js needed if IE versions less than IE8 -->

<script src="json2.js"></script>


// Will be triggered when country name was changed

function callRegCountry(){

 var countryName=$('#countryRows').val();//Will Get Selected Country

  $('#cityRows option:gt(0)').remove();//For removing old entries in city drop down.Since Ajax won't reload page.

  type : "POST",//request type
  url : "/AjaxJson/ControllerServlet",//Servlet name ..can be configured through web.xml
  data : {
   "flag":"retCities",//flag--to distinguish from multiple requests

  dataType : "text",
  success : function(data) {
    var citiArray=JSON.parse(data);

    if(citiArray != null){

    for(var s=0;s<citiArray.length;s++){

    var serial=citiArray[s];
    //populating drop down list

   error : function(){
    alert("some error occured while fetching city details corresponding to county "+countryName);

 <div id="loader">
 <div id="Country_loader">
    <td width="250px"><label>Choose the Country</label></td>
    <td><select id="countryRows" onchange="callRegCountry()">
     <option value="india">India</option>
     <option value="america">America</option>
 <div id="Citi_loader">
    <td width="250px"><label>Corresponding Cities</label></td>
    <td><select id="cityRows">
    <option value="-1">-Choose-</option>

Ajax Request will call servlet post method, Flag was used to separate from multiple requests. Based on that it will call corresponding method in java.

Servlet Code

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
 String flag=request.getParameter("flag");
 BusinessHandler handler=new BusinessHandler();
  try {
  } catch (Exception e) {

In this code fragment,Used two enumerations to hold the data,instead of getting data from Database. Here based on selected country ,iterating the corresponding enumeration and creating JSON object and adding that to JSON array and sending the JSON array as a response.

Java Code:

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

enum India{
enum America{

public class BusinessHandler {
 //Based on the selected country in front end corresponding enumeration will be iterated.enumeration is nothing but a list of constants. 

public void retCities(HttpServletRequest request, HttpServletResponse response) throws Exception {
 String country=request.getParameter("country");//holds selected country
JSONArray citArray=new JSONArray();
      for(India cnt:India.values()){//iterating India enum
   JSONObject citObject=new JSONObject();
   citObject.put("city", cnt);//populating JSONobject
} else {
for(America cnt:America.values()){
JSONObject citObject=new JSONObject();
   citObject.put("city", cnt);

jar files used for smooth flow:


Server used:

Apache tomcat v7.0


  1. Could you please mention the version of ezmorph.jar?. I will try this program in my eclipse and post my comments also.

  2. Please put one war file download about this program so that I can put more Comments.