In this example, we are talking to the database. You don\’t need to do anything else. Just write the logic for the database in your server-side page.
In this example, the code for the server is in the index.jsp file.
AJAX Database Example
How to make an ajax example with a database using jsp
You have to do the following:
- load the file called org.json.jar
- make a page where people can type in any text or number
- make a page on the server to handle the request
- Load the file called org.json.jar.
We put the org.json.jar file in the WEB-INF/lib directory so that you can download this example.
make a page where people can type in any text or number
On this page, we\’ve made a form for the user to fill out. The ajaxForm() function is called when the user presses any key. All of the ajax code is written inside this function.
Database Example
id | FirstName | LastName | Age | Hometown |
---|---|---|---|---|
1 | Shaym | Lal | 41 | Vrandavan |
2 | Krishan | Das | 40 | Mathura |
3 | Jadish | Lal | 39 | Ayodhya |
4 | Ram | Das | 41 | Ayodhya |
When the ready state changes, we have called the getData() function. With the help of the innerHTML property, it writes the returned data into the web page on the fly.
Example.html
<html>
<head>
<script>
var request;
function ajaxForm()
{
var v=document.formid.ids.value;
var url=\”index.jsp?val=\”+v;if(window.XMLHttpRequest){
request=new XMLHttpRequest();
}
else if(window.ActiveXObject){
request=new ActiveXObject(\”Microsoft.XMLHTTP\”);
}try{
request.onreadystatechange=getData;
request.open(\”GET\”,url,true);
request.send();
}catch(e){alert(\”Unable to connect to server\”);}
}function getData(){
if(request.readyState==4){
var val=request.responseText;
document.getElementById(\’ram\’).innerHTML=val;
}
}</script>
</head>
<body>
<marquee><h1>AJAX Database Example</h1></marquee>
<form name=\”formid\”>
Enter id:<input type=\”text\” name=\”ids\” onkeyup=\”ajaxForm()\”>
</form><span id=\”ram\”> </span>
</body>
</html>
example index.jsp
<%@ page import=\”file.sql.*\”%>
<%
String s=request.getParameter(\”val\”);
if(s==null || s.trim().equals(\”\”)){
out.print(\”Please enter id\”);
}else{
int id=Integer.parseInt(s);
out.print(id);
try{
Class.forName(\”com.mysql.jdbc.Driver\”);
Connection con=DriverManager.getConnection(\”jdbc:mysql://localhost:3306/mdb\”,\”root\”,\”12345\”);
PreparedStatement ps=con.prepareStatement(\”select * from student where id=?\”);
ps.setInt(1,id);
ResultSet rs=ps.executeQuery();
while(rs.next()){
out.print(rs.getInt(1)+\” \”+rs.getString(2));
}
con.close();
}catch(Exception e){e.printStackTrace();}
}
%>