ajax and jsp and mysql database connectivity code example

/
0 Comments
simple code for connecting mysql database and jsp page using ajax



here iam creating a html input page containing a text box,for inputting

user id .when we enter the userid in the text box the corresponding

output(username) is displayed in the same page

steps

step1.create a database called "jaga" in mysql



mysql>create database jaga;



step2.



mysql>use jaga;



step3.create table called login having two colums called id,name



insert values(1,jaga)

insert values(2,john)



step4.create a html input page called al.html the code is given below

al.html



<html>

<script>
function ajax(str){
var xmlHttp;
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlHttp=new XMLHttpRequest();
}
catch(e){
alert("your browser cant support");
}
}
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4){
document.write(xmlHttp.responseText);
}
}
var url="jag.jsp";
url=url+"?q="+str;
xmlHttp.open("POST",url,true);
xmlHttp.send(url);
}
</script>
<body>
<form method="post" name="jag" input type="text" name="deesh" onkeyup="ajax(this.value);">


</body>
</html>



step5.create a jsp page called jaga.jsp the code is given below

jaga.jsp

<%@ page import="java.sql.*" %>

<% String s=request.getParameter("q");%>

<% String result=""; %>


<%try{

Class.forName("com.mysql.jdbc.Driver");

Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/jag","root","root");

String sql = "select * from login where id='"+s+"';";

Statement st=con.createStatement();

st.execute(sql);

ResultSet rs=st.getResultSet();

while(rs.next()){

result=rs.getString(2);

}

}

catch(Exception ex){

out.println(ex);

}


%>

<% out.println(result);%>

step 6: create a folder in c:\programfiles\apachesoftwarefoundation\Tomcat 5.5\webapps\john

copy and paste the two files ,al.html and jaga.jsp in the folder john.



step 7: start tomcat server

step8: open ie(browser window)

step9: type the url http://localhost:8080/john/al.html



you can see the window like this






step 10:enter the value of id correspondinding in column name "id"


type 1 in text box you can see yhe output like this below




here value of id in column name id in the table login having corresponding value of name is jaga.tha is displayed as output

ajax and jsp ,mysql database connectivity

all the best www.johnmukkad.co.cc



You may also like