Home Jsp Combo Box Using Ajax In JSP
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Combo Box Using Ajax In JSP

Advertisement
In this section, you will learn how to use of 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 combo.jsp and getuser.jsp. When a web page ("combo.jsp")  run on browser then it will  having a Select Box Employee Id.On select emp id data come
 from database corresponding this id and auto fill the Emp Id and Employee Name. 

 

 

Step 1: Create a web page(combo.jsp) to show a form.


<%@ page import="java.sql.*" %> 
<html>
<head>
<style>
A:hover {text-decoration: none;
   
    border: 0px;
   font-size:14pt;
    color: #2d2b2b; }
</style>

<link rel="stylesheet" type="text/css" href="datepicker.css"/>
<script type="text/javascript">
function showEmp(emp_value)
{ 
	if(document.getElementById("emp_id").value!="-1")
	{
 xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
 {
 alert ("Browser does not support HTTP Request")
 return
 }
var url="getuser.jsp"
url=url+"?emp_id="+emp_value

xmlHttp.onreadystatechange=stateChanged 
xmlHttp.open("GET",url,true)
xmlHttp.send(null)

	}
	else
	{
		 alert("Please Select Employee Id");
	}
}

function stateChanged() 
{ 
	document.getElementById("ename").value ="";
	document.getElementById("emp_id").value ="";
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
 { 
	
  var showdata = xmlHttp.responseText; 
    var strar = showdata.split(":");
	
	 if(strar.length==1)
	 {
		 	document.getElementById("emp_id").focus();
		  alert("Please Select Employee Id");
		  document.getElementById("ename").value =" ";
	document.getElementById("emp_id").value =" ";

	 }
	 else if(strar.length>1)
	 {
	var strname = strar[1];
	document.getElementById("emp_id").value= strar[2];
	document.getElementById("ename").value= strar[1];
	 }
	
 } 
}

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;
}
</script>

</head>
<body>
<form name="employee">
<br><br>
<table border="0" width="400px" align="center" bgcolor="#CDFFFF">
<div id="mydiv"></div>
   <tr><td><b>Select Employee Id</b></td><td> 
	   <select name="semp_id" onchange="showEmp(this.value);">
	   <option value="-1">Select</option> 
<%
Connection conn = null;
    String url = "jdbc:mysql://localhost:3306/";
    String dbName = "user_register";
    String driver = "com.mysql.jdbc.Driver";
    String userName = "root"; 
    String password = "root";

    int sumcount=0; 
	Statement st;
    try {
      Class.forName(driver).newInstance();
	 
      conn = DriverManager.getConnection(url+dbName,userName,password);
	    String query = "select * from employee_details";
	
       st = conn.createStatement();
	   ResultSet  rs = st.executeQuery(query);
	   %>
	  
	   <%
	  while(rs.next())
		{
		  %>
		  
		   <option value="<%=rs.getString(1)%>"><%=rs.getString(1)%></option> 
			
  <%
		}
  %>
     
  <%
     
	}
	catch (Exception e) {
      e.printStackTrace();
    }	
%>
 </select>
</td></tr>
<tr><td ><b>Employee Id:</b></td><td>
<input  type="text" name="emp_id" id="emp_id" value=""></td></tr>
<tr><td><b>Employee Name:</b></td><td>
<input  type="text" name="emp_name" id="ename" value=""></td></tr>
</table>
</form>    
<table border="0" width="100%" align="center">
<br>
<br>
</table>
</body>
</html>

 

Step:2Create a web page (getuser.jsp)  to retireve the data from database.

<%@ page import="java.sql.*" %> 
      <%
      String emp_id = request.getParameter("emp_id").toString();
      String  data ="";
      Connection conn = null;
    String url = "jdbc:mysql://localhost:3306/";
    String dbName = "user_register";
    String driver = "com.mysql.jdbc.Driver";
    String userName = "root"; 
    String password = "root";
    int sumcount=0; 
	Statement st;
    try {
      Class.forName(driver).newInstance();
      conn = DriverManager.getConnection(url+dbName,userName,password);
	    String query = "select * from employee_details where  eid='"+emp_id+"'";
       st = conn.createStatement();
	   ResultSet  rs = st.executeQuery(query);
	   while(rs.next())
		{
		    data = ":" + rs.getString(2) + " " + rs.getString(3) +":"+ emp_id;
		}
		out.println(data);
	}
	catch (Exception e) {
      e.printStackTrace();
    }
 %>
    


Successful Output of the program:

 


Download the full web application shows here.

Download the application

Advertisement

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: July 26, 2008

Ask Questions?    Discuss: Combo Box Using Ajax In JSP   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
Priti Sharma
August 13, 2011
using ajax with struts

i have no knowledge of using ajax.i want to use it in my website build in struts framework.can u please help.
PRITI SHARMA
August 13, 2011
AJAX WITH JAVA

I WANT TO USE AJAX WITH STRUTS FRAMEWORK.I HAVE NO KNOWLEDGE OF USING AJAX.
jitendra
August 30, 2011
captcha

captcha in html with ajax and jsp
dCandan
January 23, 2013
AutoCombo

Thanks. Very Very Thanks.
Basil
November 28, 2011
Combobox not coming in JSP using AJAX

Hi, I need to make a Combobox with dynamic values. On the change of Year or Month, i want to change the values in the Week combobox. I am able to get the values back to the screen after the Ajax call. But the combobox style class is not getting called.Its displaying as text values as below 3/1/2011-7/1/201110/1/2011-14/1/201117/1/2011-21/1/201124/1/2011-28/1/201131/1/2011-31/1/2011 Kindly help me Below is my code : // Ajax call method in JSP function showWeek() { if(document.forms[0].reportFrequency != null && document.forms[0].reportFrequency.value =='Weekly') { var selectedYear = document.forms[0].selectYear.value; var selectedMonth = document.forms[0].selectMonth.value; var weeks = getWeek(selectedYear,selectedMonth); // this js function will get the values for the week var xmlHttp=null; xmlHttp=GetXmlHttpObject(xmlHttp); if (xmlHttp==null) { alert ("Browser does not support HTTP Request"); return; } var url="/Web/reports/getWeeks.jsp"; url=url+"?Weeks="+weeks; xmlHttp.onreadystatechange= stateChanged; xmlHttp.open("GET",url,true); xmlHttp.send(null); } } function stateChanged() { if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { document.getElementById("Report8").innerHTML=xmlHttp.responseText; } } function GetXmlHttpObject() { if (window.XMLHttpRequest) { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } else if(window.XMLHttpRequest) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } return xmlHttp; } ------------ // weeks has display in below div id <div id="Report8" style="display:none"> </div> ------------------------------ getWeeks.jsp response.setContentType("text/html"); response.setHeader("Cache-Control","no-cache"); String weeks = request.getParameter("Weeks"); String[] totalWeeks = weeks.split(":"); String combo="<html:select property=\"selectWeek\" styleClass=\"combobox\">"; for (int i=0;i<totalWeeks.length;++i) { System.out.println(" weeks :"+totalWeeks[i]); combo=combo+"<option value=\""+totalWeeks[i]+"\">"+totalWeeks[i]+"</option>"; } combo=combo+"</html:select>"; response.getWriter().write(combo);
Mahitha
January 11, 2012
need a code

can you please help me with how to retrieve the data from the database and consolidate it based on priority using servlet?
Chirag`
January 21, 2012
Not Working

i have already made table in my db and made all the necessary changes but it doesn't populate list of emp_id in combo box ............. Not Working
biswaranjan
March 6, 2012
ajax and jsp

it solved my problem completely........ thnks roseindia.. i suggest to give more example on ajax
Akash Jain
March 12, 2012
Problem related to Combo Box using ajax in jsp

I have copied the code from "Combo box using ajax in jsp" and created the database too .... Although the jsp shows the connected values of EMPID but when i change the selection of combo box it gives the alert message box of "Please Select Employee ID" As i dont know much about ajax please help by the Code in "Combo Box using Ajax in JSP" by rose india :-) Thanx in advance
Sourav Roy
April 8, 2012
Combo Box

thanks for the code
Alpesh Patel
April 13, 2012
JSP

can i do same things in a single jsp page. if i select one item in combo box according to first combo value the second combo will display value.same page as well as same table.
Ashish
May 1, 2012
How to do it without using scriplets?

How to do it without using scriplets?
NaveenRaj
May 15, 2012
Thanks! Not Bad to get an idea. But,

Could you show me that while we are using two select box.one contains states and another one contain district of those related states. By using AJAX in jsp; when we select the state, those corresponding district will be automatically loaded. I tried and got the output too. But, my output is like just adding the fields in the jsp page into that district table data field.
amit
September 7, 2012
confused !!!

in this file , how you come to know that emp_name is in "strar[1]" And emp_id is in "strar[2]" .. if i have more fields in table then how we will come to know about these ...
Jack Juma
March 5, 2014
Jsp

Congrat. This thing has been disturbing me for the last two weeks. Thanks. But the question is, what if I want to show more than one field, say, department, grade etc from database to be displayed at the same time? Assistence pls
Jack Juma
March 5, 2014
Jsp

Good Lord, this thing has been disturbing me for the last two weeks. Thanks But the problem is, how can I show more than one text box eg name, department, grade etc at the same time? Jack
DMCA.com