Selection With Ajax and JSP

Ads
 

Selection With Ajax and JSP

I am working at a jsp page using ajax for country , state, city selection. so if he select country it will populate the state and city selection (both). After selecting country if he select city it will populate the state selection and if he select the state it will populate the city. I am doing it through two jsp pages only. Country1.jsp :

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

Insert title here

      </head>  
      <body>  
      <table border="1">
      <tr><th>Country</th><th>State</th><th>City</th></tr>
      <tr><td>
      <select id='count' name='country' onchange="showState()">  
       <option value="none">Select</option>
       <%
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
       Connection con = DriverManager.getConnection("jdbc:odbc:senior");
       Statement stat = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
            ResultSet.CONCUR_READ_ONLY);
       ResultSet rs = stat.executeQuery("Select country from hotel");

       while(rs.next())
    {
           String co=rs.getString("country");

           %>

        <option value="co"><%=co%></option>
  <%
  }
 %>
  </select> 
  </td>
  <td id='change'><select id='stat' name='state' >  
  <option value='-1'></option>  
  </select>
  <select id='cit' name='city' >  
  <option value='-1'></option>  
  </select>

  </tr>
  </table>
  </body> 
  </html>


**Country2.jsp**



 <%@page import="java.sql.*"%>
<%
String country=request.getParameter("count");
String city=request.getParameter("city");
String state=request.getParameter("state");
 String buffer="<select id='stat' name='state' onchange='showCity();'><option value='-1'>Select</option>"; 
 String buffer2="<select id='cit' name='city' onchange='showstate();'><option value='-1'>Select</option>";  
 try{
     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
     Connection con = DriverManager.getConnection("jdbc:odbc:senior");
     Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
            ResultSet.CONCUR_READ_ONLY);
 ResultSet rs=null;
 ResultSet rs2=null;
 if(country!=null && city==null && state==null ){
     rs = stmt.executeQuery("Select state from hotel where country='"+country+"' ");

     while(rs.next()){
           buffer=buffer+"<option value='"+rs.getString("state")+"'>"+rs.getString("state")+"</option>"; 
           }

     rs = stmt.executeQuery("Select city from hotel where country='"+country+"' ");
     while(rs.next()){
           buffer2=buffer2+"<option value='"+rs.getString("city")+"'>"+rs.getString("city")+"</option>"; 
           }


 }
 else
     if(country!=null && city!=null && state==null ){
     rs = stmt.executeQuery("Select state from hotel where country='"+country+"' AND city='"+city+"' "); 
     while(rs.next()){
           buffer=buffer+"<option value='"+rs.getString("state")+"'>"+rs.getString("state")+"</option>";  
           }

     }
 else
     if(country!=null && city==null && state!=null ){
     rs = stmt.executeQuery("Select city from hotel where country='"+country+"' AND tate='"+state+"' ");
       while(rs.next()){
           buffer2=buffer2+"<option value='"+rs.getString("city")+"'>"+rs.getString("city")+"</option>";  
           }

     } 
 buffer=buffer+"</select>";
 buffer2=buffer2+"</select>";
 buffer=buffer+buffer2;
 response.getWriter().println(buffer); 

 }
 catch(Exception e){
     System.out.println(e);
 }

 %>

The database is called senior on Microsoft access , with table called hotel(ID,Country,State,city).

View Answers

April 2, 2012 at 10:50 AM

1)country.jsp:

 <%@page import="java.sql.*"%>
 <html>
      <head>  
      <script language="javascript" type="text/javascript">  
      var xmlHttp  
      var xmlHttp
      function showState(str){
      if (typeof XMLHttpRequest != "undefined"){
      xmlHttp= new XMLHttpRequest();
      }
      else if (window.ActiveXObject){
      xmlHttp= new ActiveXObject("Microsoft.XMLHTTP");
      }
      if (xmlHttp==null){
      alert("Browser does not support XMLHTTP Request")
      return;
      } 
      var url="state.jsp";
      url +="?count=" +str;
      xmlHttp.onreadystatechange = stateChange;
      xmlHttp.open("GET", url, true);
      xmlHttp.send(null);
      }

      function stateChange(){   
      if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){   
      document.getElementById("state").innerHTML=xmlHttp.responseText   
      }   
      }

      function showCity(str){
      if (typeof XMLHttpRequest != "undefined"){
        xmlHttp= new XMLHttpRequest();
        }
      else if (window.ActiveXObject){
        xmlHttp= new ActiveXObject("Microsoft.XMLHTTP");
        }
      if (xmlHttp==null){
      alert("Browser does not support XMLHTTP Request")
      return;
      } 
      var url="city.jsp";
      url +="?count=" +str;
      xmlHttp.onreadystatechange = stateChange1;
      xmlHttp.open("GET", url, true);
      xmlHttp.send(null);
      }
      function stateChange1(){   
      if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){   
      document.getElementById("city").innerHTML=xmlHttp.responseText   
      }   
      }
      </script>  
      </head>  
      <body>  
      <select name='country' onchange="showState(this.value)">  
       <option value="none">Select</option>  
    <%
 Class.forName("com.mysql.jdbc.Driver").newInstance();  
 Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");  
 Statement stmt = con.createStatement();  
 ResultSet rs = stmt.executeQuery("Select * from country");
 while(rs.next()){
     %>
      <option value="<%=rs.getString(1)%>"><%=rs.getString(2)%></option>  
      <%
 }
     %>
      </select>  
      <br>  
      <div id='state'>  
      <select name='state' >  
      <option value='-1'></option>  
      </select>  
      </div>  

      <div id='city'>  
      <select name='city' >  
      <option value='-1'></option>  
      </select>  
      </div>
      </body> 
      </html>

2)state.jsp:

<%@page import="java.sql.*"%>
<%
String country=request.getParameter("count");  
 String buffer="<select name='state' onchange='showCity(this.value);'><option value='-1'>Select</option>";  
 try{
 Class.forName("com.mysql.jdbc.Driver").newInstance();  
 Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");  
 Statement stmt = con.createStatement();  
 ResultSet rs = stmt.executeQuery("Select * from state where countryid='"+country+"' ");  
   while(rs.next()){
   buffer=buffer+"<option value='"+rs.getString(1)+"'>"+rs.getString(3)+"</option>";  
   }  
 buffer=buffer+"</select>";  
 response.getWriter().println(buffer); 
 }
 catch(Exception e){
     System.out.println(e);
 }

 %>

April 2, 2012 at 10:51 AM

continue..

3)city.jsp:

<%@page import="java.sql.*"%>
<%
String state=request.getParameter("count");  
 String buffer="<select name='city'><option value='-1'>Select</option>";  
 try{
 Class.forName("com.mysql.jdbc.Driver").newInstance();  
 Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");  
 Statement stmt = con.createStatement();  
 ResultSet rs = stmt.executeQuery("Select * from city where stateid='"+state+"' ");  
   while(rs.next()){
   buffer=buffer+"<option value='"+rs.getString(2)+"'>"+rs.getString(3)+"</option>";  
   }  
 buffer=buffer+"</select>";  
 response.getWriter().println(buffer); 
 }
 catch(Exception e){
     System.out.println(e);
 }
 %>

We have created 3 dependent dropdown. You can create the fourth one similarly.

For the above code, we have used 3 database tables:

1)country

CREATE TABLE `country` (                                 
           `countryid` bigint(255) NOT NULL auto_increment,       
           `countryname` varchar(255) default NULL,               
           PRIMARY KEY  (`countryid`)                             
     )

2)state

CREATE TABLE `state` (                                   
          `stateid` bigint(255) NOT NULL auto_increment,         
          `countryid` int(255) default NULL,                     
          `state` varchar(255) default NULL,                     
          PRIMARY KEY  (`stateid`)                               
        )

3)city

CREATE TABLE `city` (                                    
          `cityid` bigint(255) NOT NULL auto_increment,          
          `stateid` int(255) default NULL,                       
          `city` varchar(255) default NULL,                      
          PRIMARY KEY  (`cityid`)                                
        )

Ads









Related Tutorials/Questions & Answers:
Selection With Ajax and JSP
Selection With Ajax and JSP  I am working at a jsp page using ajax for country , state, city selection. so if he select country it will populate the state and city selection (both). After selecting country if he select city
Selection based on other selection in jsp
selection on same jsp page such that when someone select a category only the products...Selection based on other selection in jsp  I am trying to create a jsp page. Where I am having a select list containing category name and for each
Advertisements
jsp and ajax
jsp and ajax  how to enable or disable textbox using radio buttons by using jsp and ajax
jsp & ajax
jsp & ajax  how to enable or disable textbox using radio buttons by using jsp and ajax? plz help me.... i m new in jsp & ajax
checkbox selection in jsp
checkbox selection in jsp  hey guys i am working on a web based project using jsp. In my project i am having 9 check boxes in 3 rows in the same form. I want to select i check box from each row and also i want to avoid many
Jsp and ajax
Jsp and ajax  Hi I am using jsp and ajax.I am retrieving...; function ajax(str){ var xmlHttp; var i; var config=document.getElementById..."; url=url+"?q="+config+"&q1="+config1; xmlHttp.open("POST",url,true
Jsp and ajax
Jsp and ajax  Hi I am using jsp and ajax.I am retrieving...; function ajax(str){ var xmlHttp; var i; var config=document.getElementById..."; url=url+"?q="+config+"&q1="+config1; xmlHttp.open("POST",url,true
Jsp and ajax
Jsp and ajax  Hi I am using jsp and ajax.I am retrieving...; function ajax(str){ var xmlHttp; var i; var config=document.getElementById..."; url=url+"?q="+config+"&q1="+config1; xmlHttp.open("POST",url,true
Jsp and ajax
Jsp and ajax  Hi I am using jsp and ajax.I am retrieving...; function ajax(str){ var xmlHttp; var i; var config=document.getElementById..."; url=url+"?q="+config+"&q1="+config1; xmlHttp.open("POST",url,true
ajax in jsp
ajax in jsp  i m not able to compare string with the responseText value, though the value in the responsetext is of string type. my code: login.jsp <html> <head> <meta http-equiv
ajax in jsp
ajax in jsp  i m not able to compare string with the responseText value, though the value in the responsetext is of string type. login.jsp: print("<html> <head> <meta http-equiv="Content-Type" content="text
How to use ajax in jsp?
How to use ajax in jsp?  Hi, How i can access the server-side data in JSP using the Ajax? Thanks   Hi, You can use the Ajax code to access the server side data from JSP page. Check the tutorial Combo Box Using Ajax
jsp+ajax validation
jsp+ajax validation  hi, I have created the jsp form (course... 60% in the drop down list .how to validate student from using ajax and jsp... have created student jsp form where it should display register number
ajax code for jsp
ajax code for jsp  How to write ajax code to retrieve information on to particular part of webpage when we select option from drop down box
Modifying a single row of database based on selection in jsp
Modifying a single row of database based on selection in jsp  Hi guys...://www.roseindia.net/answers/viewqa/JSP-Servlet/18899-data-grid-with-edit-and-delete-options-at-each-row-.html http://www.roseindia.net/answers/viewqa/JSP
The AJAX JSP Tag Library
The AJAX JSP Tag Library       The AJAX JSP Tag Library is a set of JSP tags that simplify the use of Asynchronous JavaScript and XML (AJAX) technology in JavaServer Pages. This tag
Ajax validation - JSP-Servlet
Ajax validation  How to fade out the images when an onblur function is called moving from a text box to another?? can anyone help out with with the code
Ajax using jsp
Ajax using jsp  <%@ page import="java.io.*" %> <%@ page import="java.util.*" %> <%@ page import="java.sql.*" %> <%@ page import...); } %> Is there Any error...........In first Page I use ajax for displaying
ajax using jsp
ajax using jsp  <%@ page import="java.io.*" %> <%@ page import="java.util.*" %> <%@ page import="java.sql.*" %> <%@ page import="java.util.StringTokenizer" %> <%@ page import="java.lang.*" %> <
Ajax not working in jsp
Ajax not working in jsp  I'm using Netbean, Ajax validation in the following code is not working the code succesfully run for first UID validation...; frmMain.elements[i].valid; } } return blnValid; } //if Ajax
Drop-down text selection in jsp/html
Drop-down text selection in jsp/html  Hi, I am trying to create JSP page where I have two drop-downs. There are two-sets of data - First set Categories- Movies, Books, Music and the Second set Genres- Action,Comedy,Romantic
DropDown in ajax+jsp
DropDown in ajax+jsp  I have four dropdown if i select first dd then only corresponding values must be there in 2nd dd,same with 3 and 4 and onchangfe it would not refresh the whole page.   Hi Friend, Try the following
application using AJAX and JQuery and also use JSP
application using AJAX and JQuery and also use JSP   i need create an application using AJAX and JQuery and also use JSP
How to create textbox on combo value selection using javacsript in jsp?
How to create textbox on combo value selection using javacsript in jsp?  dynamically create textbox on combo value selection. when select multiple values then create multiple textboxes
JQuery-JSP AJAX example not working
JQuery-JSP AJAX example not working  Hi, I while back ran you... started with AJAX)), I was able to get it working. Just recently, I have been working on some additional development code using AJAX and I was getting some
how to implement ajax in struts2 to operate on selectbox in jsp
how to implement ajax in struts2 to operate on selectbox in jsp  I am doing a project on struts2 in which i have a jsp page which has 2 select boxes... the ajax wll be called and retrieve me the blocks under the selected district
Ajax
Ajax  how to impliment ajax in registration table using jsp-servlet
Combo Box Using Ajax In JSP
Combo Box Using Ajax In JSP       In this section, we develop an  application to Select the Data from database using Ajax in combo box. We created two file
access image from ajax store in mysql using jsp
access image from ajax store in mysql using jsp  access image from ajax store in mysql using jsp (code to access image captured by camera and store in mysql
Popup Window using Ajax In JSP
Popup Window using Ajax In JSP  ... Window application using Ajax in JSP. For this, we will create the following...;jsp:forward page="InsertData.jsp" /> <% } else
how to get popup fro servelt to jsp by using ajax........
how to get popup fro servelt to jsp by using ajax........  how to get popup fro servelt to jsp by using ajax........ I went popup in jsp page when my form submit successfully.....through servlet can any buddy give r explian how

Ads