Tuesday, 18 October 2011

Auto Fill Combobox in JSP using Ajax

Data Base Design

Database Name : country
Table : Country
create table country(
id int,
name varchar(30)
);

Table : State
create table state(
id int,
name varchar(30),
cid int
);

Table : City
create table city(
id int,
name varchar(30),
sid int
);

Code:

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" import="java.sql.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>

<script type="text/javascript">
function getState()
{
var xmlHttp;
var x = document.getElementById("fillState");
x.length = 0;
document.getElementById("fillCity").length = 0;

if(x.value!=-1){
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    try
      {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    catch (e)
      {
      alert("Your browser does not support AJAX!");
      return false;
      }
    }
  }
  xmlHttp.onreadystatechange=function()
    {
    if(xmlHttp.readyState==4)
      {
        var showdata = xmlHttp.responseText;
        var str = showdata.split(":");
        var len = str.length;
          var i =0;
          for(i=0;i<len;){
              var option=document.createElement("option");
            option.text= str[i];
            option.value = str[i+1];
            try
              {
              // for IE earlier than version 8
              x.add(option,x.options[null]);
              }
            catch (e)
              {
              x.add(option,null);
              }
            i=i+2;
          }
      }
    }
  var val = document.getElementById("fillCountry").value;
  var url = "getOption.jsp?opt="+val+"&table=state";
  xmlHttp.open("GET",url,true);

  xmlHttp.send(null);
}

  }
 
  function getCity(){
      var xmlHttp;
      var x = document.getElementById("fillCity");
      x.length = 0;

      if(x.value!=-1){
      try
        {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
        }
      catch (e)
        {
        // Internet Explorer
        try
          {
          xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
          }
        catch (e)
          {
          try
            {
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
          catch (e)
            {
            alert("Your browser does not support AJAX!");
            return false;
            }
          }
        }
        xmlHttp.onreadystatechange=function()
          {
          if(xmlHttp.readyState==4)
            {
              var showdata = xmlHttp.responseText;
              var str = showdata.split(":");
              var len = str.length;
                var i =0;
                for(i=0;i<len;){
                    var option=document.createElement("option");
                  option.text= str[i];
                  option.value = str[i+1];
                  try
                    {
                    // for IE earlier than version 8
                    x.add(option,x.options[null]);
                    }
                  catch (e)
                    {
                    x.add(option,null);
                    }
                  i = i+2;
                }
            }
          }
        var val = document.getElementById("fillState").value;
        var url = "getOption.jsp?opt="+val+"&table=city";
        xmlHttp.open("GET",url,true);

        xmlHttp.send(null);
      }
  }
</script>
<table>
<form name="myForm">
<%
Connection con = null;
Statement stat = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/country";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "dreams";
try {
    Class.forName(driver).newInstance();
    con = DriverManager.getConnection(url, userName, password);
    stat = con.createStatement();
    rs = stat.executeQuery("Select * from Country");
%>
<tr>
<td>Country : </td>
<td>
<select id ="fillCountry" onChange="getState();">
<option value=-1>Select</option>
<%
    while(rs.next()){
        out.println("<option value="+rs.getString(1)+">"+rs.getString(2)+"</option>");
    }
}
catch (Exception e) {
    e.printStackTrace();
}

%>
</select>
</td>
</tr>
<tr>
<td>State : </td>
<td>
<select id = "fillState" onChange = "getCity();">
<option>Select</option>
</select>
</td>
</tr>
<tr>
<td>City : </td>
<td>
</select>
<select id = "fillCity">
<option>Select</option>
</select>
</td>
</tr>
</form>
</table>
</body>
</html>


getOption.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" import="java.sql.*"%>

<%
Connection con = null;
Statement stat = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/country";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "dreams";
int id = Integer.parseInt(request.getParameter("opt"));
String table = request.getParameter("table");
try {
    Class.forName(driver).newInstance();
    con = DriverManager.getConnection(url, userName, password);
    stat = con.createStatement();
    if(table.equals("state")){
        rs = stat.executeQuery("Select * from state where cid = "+id);
    }else if(table.equals("city")){
        rs = stat.executeQuery("Select * from city where sid = "+id);
    }
    String str = "";
    while(rs.next()){
        str = str + rs.getString(2) + ":";
        str = str + rs.getString(1) + ":";
    }
    str = str.substring(0,str.length()-1);
    out.println(str);
}
catch (Exception e) {
    e.printStackTrace();
}

%>

No comments:

Post a Comment