AJAX connectivity with Database:
- In this example, we are interacting with the database. You don't have to make any extra effort. Only write the database logic in you server side page.
- In this example, we have written the server side code inside the index.jsp file.
Steps to create ajax example with database through jsp:
- You need to follow following steps:
- load the org.json.jar file
- create input page to receive any text or number
- create server side page to process the request
- Load the org.json.jar file
- In this page, we have created a form that gets input from the user. When user press any key sendInfo() function is called. We have written all the ajax code inside this function.
- We have called the getInfo() function whenever ready state changes. It writes the returned data in the web page dynamically by the help of innerHTML property.table1.html
- <html>
- <head>
- <script>
- var request;
- function sendInfo()
- {
- var v=document.vinform.t1.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=getInfo;
- request.open("GET",url,true);
- request.send();
- }catch(e){alert("Unable to connect to server");}
- }
- function getInfo(){
- if(request.readyState==4){
- var val=request.responseText;
- document.getElementById('amit').innerHTML=val;
- }
- }
- </script>
- </head>
- <body>
- <marquee><h1>This is an example of ajax</h1></marquee>
- <form name="vinform">
- Enter id:<input type="text" name="t1" onkeyup="sendInfo()">
- </form>
- <span id="amit"> </span>
- </body>
- </html>
create server side page to process the request:
In this jsp page, we printing the id and name of the employee for the given id.index.jsp
- <%@ page import="java.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","root");
- PreparedStatement ps=con.prepareStatement("select * from emp 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();}
- }
- %>