Newsletter |
Ajax Onchange Fetch The Data From The Database
Ajax » on Oct 20, 2011 { 34 Comments } By Sivateja
Let us see how to fetch the data from database onchange of drop down, actually this is the real time scenario, 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
<html> <head> <script type="text/javascript"> function loadXMLDoc() { var xmlhttp; var keys=document.dummy.sele.value var urls="https://www.java4s.com:2011/On_select_from_database_dropdown/db_fetch.jsp?ok="+keys if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4) { var some=xmlhttp.responseXML.documentElement; document.getElementById("a").innerHTML=some.getElementsByTagName("empno")[0].childNodes[0].nodeValue; document.getElementById("b").innerHTML=some.getElementsByTagName("empname")[0].childNodes[0].nodeValue; document.getElementById("c").innerHTML=some.getElementsByTagName("empaddr")[0].childNodes[0].nodeValue; } } xmlhttp.open("GET",urls,true); xmlhttp.send(); } </script> </head> <body> <form name="dummy"> <select name="sele" onchange="loadXMLDoc()"> <option>value</option> <option value="100">100</option> <option value="101">101</option> </select> </form> id: <span id="a"></span><br> name: <span id="b"></span><br> address: <span id="c"></span> </body> </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
Output
Click Here To Check The Output
::. About the Author .:: | ||
Comments
34 Responses to “Ajax Onchange Fetch The Data From The Database”
I like this post, enjoyed this one appreciate it for posting .
Hello..
When am executing this program am getting error in javascript at line number 21 saying as xmlhttp.responseXML is null. Am using mysql database. I got to know this from the error console of the mozilla browser.
I did not understand purpose of
1. function loadXMLDoc1()
2.document.getElementById(“a”).innerHTML=some.getElementsByTagName(“empno”)[0].childNodes[0].nodeValue;
Please provide explaination.
@Mohammed Vaseem
– Sorry friend, i overlooked that function while executing [ function loadXMLDoc1() removed now ].
– document.getElementById(“a”).innerHTML=some.getElementsByTagName(“empno”)[0].childNodes[0].nodeValue;
Here document.getElementById(“a”).innerHTML means in place of span id=”a”, we are printing ‘empno‘ which is in the jsp page [ that is XML syntax ]
Hello,
Again am getting the same error at the same line. Please help.
@Mohammed Vaseem
I have tested, every thing is working fine from my end.
Check once and make your jsp file is able to fetch the values from the database and test whether it is able to print the values by removing xml tags [ out.println(rs.getInt(1)) ], your jsp file must work.
Thank you for your extreme help.
I did mistake in the line 8. I Directly copy pasted the program. After giving correct path i got output.
@Mohammed Vaseem
Gosh, any ways good to here that you got it 🙂
i like your website very much.its very easy to understand..
while testing ajax program,its not working,i can’t understand this line
var urls=”https://www.java4s.com:2011/On_select_from_database_dropdown/db_fetch.jsp?ok=”+keys
–>how Index.html will link to db_fetch.jsp
thank you
Bikash
@Bikash
See line number 27, we have open() method in xmlhttp object right, once program flow reaches to this line, Ajax object will sends the request to the url in ‘urls’ variable.
There we used to write business logic and all.
Hai Bikash,
You just simply use the path of ‘db_fetch.jsp’ of your project.It will work.
what i mean is that, if Your db_fetchjsp is in the same folder, just use
var url=”db_fetch.jsp?ok=”+key
hope it will work..
with due respect —
sir ! Although i have understood the full code , but still i am having trouble in executing the same. you have written
” var some=xmlhttp.responseXML.documentElement; “, but the response is coming from an jsp file then why “responseXML” (number-1) and i have put an alert after this line and that alert is also not working.
so i request you to please guide me accordingly as soon as possible…
@Amith
Though we are getting the response from jsp, we must specify the type of response(responseXML) there.
Hello sir i am getting error when i execute using xmlhttp.open(“GET”,”db_fetch.jsp”,true); when i am using responseText its working but i cant able to get response using responseXML……plz help.
I got this error
SEVERE: Servlet.service() for servlet [jsp] in context with path [/AjaxFetch] threw exception [java.lang.NumberFormatException: For input string: “”] with root cause
java.lang.NumberFormatException: For input string: “”
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
please help
Wht to do if we have datatype of column is varchar….?
because my empno is of varchar…
it is working but i have problem when i have a ‘&’ character in a string .it does not give result for eg;
if i have “me & you” it does not reaqd this.
i’m not getting the output even though i did everything as it shown above.
i am not getting in jsp
even i mention additional out.println’s
sir i tried it but im not getting anything when im selecting a value
sir, i wish to display those fetched data to my text box in index.html is it possible???? and what is the need of web.xml
when i execute the program it is showing null for documentElement, pls help me
Hiii sir,ur tutorial is good.how to get the value in textbox when fetches the data from database
sir..i use oracle 11g expressedition…in this ojdbc14 is not there..
what should i do??
and where the classes12 will be??
pls help…
would you like to show this out in html table
@Java4s could you please explain this example for us?
Thanks in advance.
and what will be the query for mysql in place of oracle;
want the same program
Hi
I have tried this example i dont know why the url in the index.html is not able to load db_fetch.jsp.
my url in index.html file is url=”http://localhost:8081/AjaxEx1/db_fetch.jsp?ok=”+keys
can u plz any one help me ..?
Very Helpfull…
working fine //////
index.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
var key=document.dummy.sele.value
var urls="pass.jsp?ver="+key;
if(window.XMLHttpRequest)
{
xmlhttp =new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
var some=xmlhttp.responseXML.documentElement;
document.getElementById("a").innerHTML=some.getElementsByTagName("empno")[0].childNodes[0].nodeValue;
document.getElementById("b").innerHTML=some.getElementsByTagName("empname")[0].childNodes[0].nodeValue;
}
}
xmlhttp.open("GET",urls,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form name="dummy">
<select name="sele" onchange="loadXMLDoc()">
<option>value</option>
<option value="100">100</option>
<option value="101">101</option>
</select>
</form>
id : <span id="a" ></span><br>
name: <span id="b"></span><br>
</body>
</html>
————————————–
pass.jsp
<%@page import="java.io.*,java.sql.*"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%
response.setContentType("text/xml");
String sn=request.getParameter("ver");
int i=Integer.parseInt(sn);
Class.forName("com.mysql.jdbc.Driver");
Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/ajax","root","4190");
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("</emp>");
}
rs.close();
st.close();
con.close();
%>
this code is not working for me please help me out from this
Great tutorial. This tutorial have a lots of good examples and resources. It was extremely helpful. This was so easy to follow and exactly what I was looking for.
Thanks.
Hi SivaTeja,
in page db_fetch.jsp the value is not coming in the variable named key in the below expression.
var keys=document.dummy.sele.value
i am checking by printing the value by document.write(keys),
please help me out
Great tutorial sir.But please provide the tutorial of ajax where server side programming will be in php language.
String sn=request.getParameter("ok");// in this line we get ok parameter but ok is not defile
int i=Integer.parseInt(sn);
And i retrieve the data from database that is displayed in that corresponding textbox
i want to display the result in textbox very argent reply fast bro.
I did not understand purpose of
1. function loadXMLDoc1()
2.document.getElementById(“a”).innerHTML=some.getElementsByTagName(“empno”)[0].childNodes[0].nodeValue;