Results 1 to 3 of 3
  1. #1
    jerald55 is offline Member
    Join Date
    Jan 2011
    Posts
    3
    Rep Power
    0

    Post JSP with Ajax Please Help Me

    Hi i'm new to Ajax..,
    i want to generate Dynamic combo box.
    i did it in JSP using onchange event but that full page is loading for each event so my Team Leader advice me to use Ajax.

    in the form i load state in combo box1 default. Now i need to use of this value i need to change 2nd combo box.,

    below my coding are coming please help me...,

    Form1.jsp

    <%@ page import="java.sql.*"%>
    <%@ page import="java.io.*"%>
    <%@ page import="java.text.*"%>
    <%@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>
    <script language="java" type="text/javascript" >
    function GetXmlHttpObject()
    {
    var xmlHttp=null;
    try
    {
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
    }
    catch (e)
    {
    // Internet Explorer
    try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }catch (e)
    {
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    }
    return xmlHttp;
    }
    var xmlObj = GetXmlHttpObject();

    function getCityData()
    {
    var stateValue = document.getElementById("State").value;

    url = "http://localhost:8085/NewForm/getCity.jsp?State="+stateValue;
    alert(url);
    xmlObj.open("GET",url);

    xmlObj.onreadystatechange = function() {
    alert(xmlObj.status);
    //alert(xmlObj.readystate);
    if(xmlObj.readystate == 4 & xmlObj.status == 200)
    alert(xmlObj.readystate);
    {
    alert("jerald");
    var id = document.getElementById("City").innerHtml;
    alert(id);
    var result = xmlObj.responseText;

    var s = result.split(',');
    var indx = 1;
    for(indx=1; indx < s.length; indx++)
    {
    id.options[s[indx]] = new Option(s[2],s[1]);
    }
    }
    }
    xmlObj.send(null);
    }


    function getAreaData()
    {
    var cityValue = document.getElementById("City").value;
    var url = "getArea.jsp?City="+cityValue;
    alert(url);
    xmlObj.open("GET", url)
    alert("3");
    xmlObj.onreadystatechange = function() {


    if(xmlObj.readystate == 4 & xmlObj.status == 200)
    {
    alert(xmlObj.statusText);
    var id = document.getElementById("Area");
    var result = xmlObj.responseText;

    var s = result.split(',');
    var indx = 1;
    for(indx=1; indx < s.length; indx++)
    {
    id.options[indx] = new Option(s[2],s[1]);
    }
    }
    }

    xmlObj.send(null);
    }
    </script>
    </head>
    <title>Master</title>
    <style rel="stylesheet" type="text/css" media="screen">
    form
    {
    margin: 4em auto;
    width: 75%;
    }
    </style>
    </head>

    <body bgcolor="orange" text='black'>
    <form name="form1" action="http://localhost:8085/NewForm/dil_ProjectMaster.jsp" method="POST" onsubmit="return (checkform(this) && ValidateDate())";>

    <div align="center">
    <table border='0' height="500" width="1000" text='black' colspan='4' bgcolor="orange">

    <tr>
    <th colspan="4" ><font size="5">PROJECT MASTER</th>
    </tr>
    <tr>
    <td><font size="5">Project Code</td>
    <td><input type="text" name="dil_ProjectCode" id="dil_PC"></td>


    <td><font size="5">Project Name</td>
    <td ><input type="text" name="dil_ProjectName" id="dil_PN">

    </tr>

    <tr>
    <td><font size="5">Work Level1</td>
    <td >
    <%
    Connection con = null;
    PreparedStatement stmt= null;
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    con = DriverManager.getConnection("jdbcracle:thin:@loc alhost:1521:xe","distil","distil");
    %>


    <%

    stmt = con.prepareStatement("select S_ID,STATE from mt1");
    ResultSet rs1=stmt.executeQuery();
    %>
    <select name="State" id="State" onchange=" return getCityData();">
    <option value="0">------Please Select------</option>

    <%
    while(rs1.next())
    {
    %> <option value="<%=rs1.getString(1)%>"><%=rs1.getString(2)% ></option>
    <%}
    rs1.close();
    %>
    <option selected="selected" value="<%=request.getParameter("State")%>"><%=requ est.getParameter("State")%></option>
    </select>
    </td>



    <td><font size="5">Work Level2</td>

    <td>
    <select name="City" onchange="return getAreaData()";>
    <option value="0">------Please Select------</option>
    </select>
    </td>


    <tr>
    <td><font size="5">Work Level3</td>
    <td>

    <select name="Area">
    <option value="0">------Please Select------</option>
    </select>
    </td>

    <td><font size="5">Notes</td>
    <td><input type="text" name="dil_Notes"></td>
    </tr>

    <tr>
    <td><font size="5">Project Start Date</td>
    <td><input type="text" size="20" name="dil_ProjectStartDate">


    </td>


    <td><font size="5">Project End Date</td>
    <td><input type="text" size="20" name="dil_ProjectEndDate">

    </td>
    </tr>
    <tr>
    <td></td>
    <td><input type="Submit" value="Save" >
    </td>
    <td>
    <input type="Button" value="New" onClick="location.href='http://localhost:8085/NewForm/Form1.jsp'"></td>

    </tr>


    </table>
    </form>

    <%
    stmt.close();
    con.close();
    %>
    </body>
    </html>


    getCity.jsp

    <%@ page import="java.sql.*"%>
    <%@ page import="java.io.*"%>
    <%@ page import="java.lang.*"%>
    <%@ page import="java.text.*"%>
    <%@page contentType="text/html" pageEncoding="UTF-8" language="java"%>

    <%

    String stateId = null;
    Connection con = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;


    try
    {
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

    con = DriverManager.getConnection("jdbcracle:thin:@loc alhost:1521:xe","distil","distil");


    stateId = request.getParameter("State");

    String query = "select C_ID,CITY from mt2 where S_ID='"+stateId+"'";

    stmt = con.prepareStatement(query);

    rs = stmt.executeQuery();
    String data = null;
    while(rs.next())
    {
    data = ":" + rs.getString(1) + " " + rs.getString(2);
    }

    out.println(data);

    }

    catch (SQLException ex){
    System.err.println(ex.getMessage());
    }
    catch (Exception e){
    e.printStackTrace();
    }
    finally{

    rs.close();
    con.close();
    stmt.close();

    }
    %>

    similar for getArea.jsp and one more jsp for saving data into database..,

    Please help meeeeeeeee.,

  2. #2
    jerald55 is offline Member
    Join Date
    Jan 2011
    Posts
    3
    Rep Power
    0

    Post Jsp with Ajax Please Help Me

    This Ajax for getCity.jsp

    function GetXmlHttpObject()
    {
    var xmlHttp=null;
    try
    {
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
    }
    catch (e)
    {
    // Internet Explorer
    try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }catch (e)
    {
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    }
    return xmlHttp;
    }
    var xmlObj = GetXmlHttpObject();

    function getCityData()
    {
    var stateValue = document.getElementById("State").value;

    url = "http://localhost:8085/NewForm/getCity.jsp?State="+stateValue;
    alert(url);
    xmlObj.open("GET",url);

    xmlObj.onreadystatechange = function() {
    alert(xmlObj.status);
    //alert(xmlObj.readystate);
    if(xmlObj.readystate == 4 & xmlObj.status == 200)
    alert(xmlObj.readystate);
    {
    alert("jerald");
    alert(xmlObj.statusText);
    //var id =
    document.getElementById("Cit").innerHTML=xmlObj.re sponseText;
    alert(id);
    //var result = xmlObj.responseText;

    var s = result.split(',');
    var indx = 1;
    for(indx=1; indx < s.length; indx++)
    {
    id.options[s[indx]] = new Option(s[2],s[1]);
    }
    }
    }
    xmlObj.send(null);
    }

    document.getElementById("City") is Null is coming..,

    Please Help me out..,
    I'm a new Joiner in efinServe company..,



    In this program Now tried by Putting responsetext in alert it is retrieving proper City.
    but i can't able to get that in the combo box2..,

  3. #3
    go4soumya is offline Member
    Join Date
    Oct 2010
    Posts
    32
    Rep Power
    0

    Default Dynamic select menu using ajax

    hi jerald..

    first of all...try to write your login in a servlet and not in a jsp. It's a better practice and jsp is used mainly as a presentation logic.

    you can create a simple dynamically generated select menu using ajax in the following way:

    Create a javascript file : ajax_func.js
    Create an html/jsp file for frontend: view.html/view.jsp
    Create a servlet: show_city.java

    view.html: (use can also use .jsp here if u need to)
    Java Code:
    <html>
    <head>
    <title>Dynamic select menu</title>
    <script type="text/javascript" src="ajax_func.js"></script>
    </head>
    <body>
    <form name="f1">
    <table width="90%" border="0" cellpadding="6" align="center">
    <tr>
      <td>Select state: </td>
      <td>
      <select name="state" onchange="show_city(this.value)">
      <option value="state1">State1</option>
      <option value="state2">State2</option>
      </select>
      </td>
    </tr>
    <tr>
      <td>Select city: </td>
      <td><span id="cityDIV">
      <select name="city">
      <option value="state1">State1</option>
      </select>
      </span>
      </td>
    </tr>
    </table>
    </form>
    </body>
    </html>
    ajax_func.js
    Java Code:
    function show_city(state)
    { 
      	xmlHttp=CreateXmlHttpObject();
      	
      	if (xmlHttp==null)
      	{
      	alert ("Browser does not support HTTP Request");
      	return;
      	} 
    
    	var url="/projectname/show_city"; //here show_city is the servlet name
      	url=url+"?state="+state;
      	url=url+"&sid="+Math.random();
      
      	xmlHttp.onreadystatechange=stateChanged2;
      	xmlHttp.open("GET",url,true);
      	xmlHttp.send(null);
      
    }
    
    function stateChanged2() 
    { 
      	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
      	{	 
      		document.getElementById("cityDIV").innerHTML=xmlHttp.responseText; 
      	} 
    }
    
    function CreateXmlHttpObject()
      { 
      var objXMLHttp=null;
      if (window.XMLHttpRequest)
      {
      objXMLHttp=new XMLHttpRequest();
      }
    
      else if (window.ActiveXObject)
      {
      objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    
      return objXMLHttp;
    
      }
    show_city.java
    Java Code:
    .....
    
    //just writing the logic
    
    try {
                            
            	response.setDateHeader("Expires", -1);
            	
            	String responseText=new String("");
            	String query;
        		String state=(String) request.getParameter("state");
        		
        		try
        		{
        		dbcon dc=new dbcon(); 
        		Connection con=dc.connect_db(); // connect to database
        		
        		ResultSet rs=null;
        		PreparedStatement ps=null;
        				
        		query="select * from cities where states='"+state+"'";
        		ps=con.prepareStatement(query);
        		rs=ps.executeQuery();
        		responseText="<select name='city' >";
    
        		while(rs.next())
        		{
        			responseText+="<option  value='"+ rs.getString(1) +"'>"+rs.getString(1)+"</option> ";		
        		}
        		responseText+="</select>";
        	  	out.print(responseText);
        	  	con.close();
        		}
        		catch (Exception e) {
    				e.printStackTrace();
    			}
        		
        	  	
            } finally { 
                out.close();
            }
    .....

Similar Threads

  1. Can AJAX be used in JSP?
    By Bbob in forum JavaServer Pages (JSP) and JSTL
    Replies: 7
    Last Post: 12-29-2010, 10:36 AM
  2. jsp + ajax
    By sysout in forum JavaServer Pages (JSP) and JSTL
    Replies: 1
    Last Post: 07-19-2010, 11:53 AM
  3. Ajax
    By arian1978@gmail.com in forum Advanced Java
    Replies: 1
    Last Post: 11-30-2009, 03:02 PM
  4. Jsp with Ajax
    By sundarjothi in forum JavaServer Pages (JSP) and JSTL
    Replies: 16
    Last Post: 09-25-2008, 10:29 AM
  5. AJAX in JSP
    By haiforhussain in forum JavaServer Pages (JSP) and JSTL
    Replies: 8
    Last Post: 07-01-2008, 02:12 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •