Ajax json jquery Post example | Java @ Desk
Home » , » Ajax json jquery Post example

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>
<html>
<head>
<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>

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

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

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

    if(citiArray != null){

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

    var serial=citiArray[s];
    //populating drop down list
       $("#cityRows").append($("<option></option>").val(serial.city).html(serial.city));
    }
    }
    }catch(err){
     alert(err);
    }

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

</script>
</head>
<body>
 <div id="loader">
 <div id="Country_loader">
  <table>
   <tr>
    <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>
           </select>
    </td>
   </tr>
  </table>
 </div>
 <div id="Citi_loader">
  <table>
   <tr>
    <td width="250px"><label>Corresponding Cities</label></td>
    <td><select id="cityRows">
    <option value="-1">-Choose-</option>
     </select></td>
   
   </tr>
  </table>
 </div>
 </div>
</body>
</html>


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 {
 response.setContentType("text/html");
 String flag=request.getParameter("flag");
 BusinessHandler handler=new BusinessHandler();
 if(flag.equalsIgnoreCase("retCities")){
  try {
   handler.retCities(request,response);
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}


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{
 Mumbai,Hyderabad,Chennai,Delhi,Bangalore;
}
enum America{
 Mexico,NewYork,Toronto,Chicago;
}

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();
if(country.equalsIgnoreCase("india")){
      for(India cnt:India.values()){//iterating India enum
   JSONObject citObject=new JSONObject();
   citObject.put("city", cnt);//populating JSONobject
    citArray.add(citObject);
  }
} else {
for(America cnt:America.values()){
JSONObject citObject=new JSONObject();
   citObject.put("city", cnt);
   citArray.add(citObject);
}
}
 response.getWriter().write(citArray.toString());
}
}


jar files used for smooth flow:

ezmorph.jar
json-lib-2.2.2-jdk15.jar
commons-beanutils-1.7.jar
commons-collections.jar
commons-lang.jar
commons-logging-1.1.1.jar

Server used:

Apache tomcat v7.0




2 comments:

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

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

    ReplyDelete