Thursday, November 26, 2009

JQuery Country State HTML SELECT [Dropdown] AJAX Implementation using JSON

This is the basic tutorial which will help you to start with JQuery and JSON(Java Script Object Notation) Objects. The following is the Project Structure in Netbeans; I worked in Netbeans hence soJ. In this tutorial I will start with JQuery AJAX Implementation with XML Objects,

For my convenience I have not downloaded/Installed any JQuery Javascript file in the current project, Still I am referring to the JQuery Website shared JavaScript Files. Hope it will help you from getting confused to the version of JQuery and other JS Files.
JQuery AJAX Using JSON Objects.

I know whenever we hear about AJAX Country/State Drop down example will come into our mind, So I am also referring to the same. Here whenever the User changes the Country Dropdown we will update the State associated with that Country.
In this example we have only two JSP Files,
    1. indexJSON.jsp
    2. CountryStateJSON.jsp
Hope you can Apply few style sheet to make the index.jsp as followsJ, I think the image is ext-js component, any way I kept image to give you an idea.



The state information we are responding to the client as a JSON Object as follows.
LinkedHashSet statesSet = new LinkedHashSet< HTMLOption>();
        statesSet.add(new HTMLOption("1", "Kerala"));
        statesSet.add(new HTMLOption("2","Karnataka"));
        statesSet.add(new HTMLOption("3", "Delhi"));
        System.out.println("Linked Hash Map:"+statesSet);
        out.println(statesSet);

The above Code will generate the JSON Object as follows
     [   {id:1,value:'Kerala'}, 
         {id:2,value:'Karnataka'}, 
         {id:3,value:'Delhi'}   ]
The following Line of code in JSP will help to respond the Data as a Java Script File.

     response.setContentType("text/javascript");
     response.addHeader("Content-Disposition", "attachment; filename="+ "states.js");

In the current Example I am not connecting any Database for fetching the State details; I am simply updating the State drop down with My State in India and the neighborJ.We have two drop down in Our Page with ids
1. Dropdown Country id="country"
2. Dropdown State id=" stateDD"
       Country “onchange” we are calling function loadState(), which makes an JQuery AJAX Request to the CountryStateJSON.jsp, and It is handling the response as JavaScript Object(JSON), (by using the dataType TAG we are representing it) and pass the js File to the  loadStateFromJSON Function.
       By Using JSON Object Parser It iterates and retrieve all the states from JSON and Add to the state DropDown using appendState Method.
  ClearDD Method : It will remove all the options under the stateDD.
Example.
IndexJSON.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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=UTF-8">
        <title>JSP Page>/title>
        
        
    </head>
    <body>

Hello World!

Country : State : </body> </html>


The countryState.jsp is simply receiving the countryId from request and responding a static states xml file.
CountryStateJSON.jsp

<%
       <@ page import="java.util.LinkedHashSet" >
       <@ page import="java.util.LinkedHashMap" >
       <@ page import="org.json.model.HTMLOption" >
       <%
        System.out.println("CountryID-----------"+request.getParameter("countryId"));
        response.setContentType("text/javascript");
        response.addHeader("Content-Disposition", "attachment; filename="
          + "states.js");
        LinkedHashSet statesSet = new LinkedHashSet();
        statesSet.add(new HTMLOption("1", "Kerala"));
        statesSet.add(new HTMLOption("2","Karnataka"));
        statesSet.add(new HTMLOption("3", "Delhi"));
        System.out.println("Linked Hash Map:"+statesSet);
        out.println(statesSet);
%>
HTMLOption.java

package org.json.model;

public class HTMLOption {

    String id;
    String value;

    public HTMLOption(String id, String value) {
        this.id = id;
        this.value = value;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "{id:"+id+",value:'"+value+"'}";
    }
}
NOTE: Here toString method need to implemented, and the data String should be as Key=Value (Eq: id = 1 ) and each entry shuld be separated by a Comma. For Multiple Values Please Refer HashSet Printing.

No comments: