Ajax On change Fetch

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Ajax Onchange Fetch The Data From The Database

 

Let us see how to fetch the data from database onchange of drop down, actually this is the real timescenario, am using jsp  you can integrate with any type of frame works ( in .java files ), concept is same.

Files Required

  • index.html
  • db_fetch.jsp
  • web.xml

Index.html

db_fetch.jsp

<%@ page import="java.io.*,java.sql.*" %>
<%@ page contentType="text/html" pageEncoding="UTF-8"%>
 
<%
 
response.setContentType("text/xml");
String sn=request.getParameter("ok");
int i=Integer.parseInt(sn);
 
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =DriverManager.getConnection("jdbc:oracle:thin:@www.java4s.com:1521:XE","system","admin");
Statement st=con.createStatement();
ResultSet rs = st.executeQuery("select * from emp where empno="+i);
if(rs.next())
{
 
out.println("<emp>");
out.println("<empno>"+rs.getInt(1)+"</empno>");
out.println("<empname>"+rs.getString(2)+"</empname>");
out.println("<empaddr>"+rs.getString(3)+"</empaddr>");
out.println("</emp>");
 
}
 
rs.close();
st.close();
con.close();
 
%>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
 
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>

 

OutPut

Note: you must have classes12.jar, ojdbc14.jar in the lib folder of you application

Database