Ajax tutorial with database using jsp

index.jsp
<br /> <%@page contentType="text/html" pageEncoding="UTF-8"%><br /> <!DOCTYPE html><br /> <html><br /> <head><br /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><br /> <title>JSP Page</title><br /> <script type="text/javascript"> var request; function sendInfo(){ var v=document.form.t1.value;//this will store textbox value. var url="Process.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);//get is a method request.send(); } catch(e) { alert("Exception Occured!!!!!!"); } } function getInfo(){ if(request.readyState===4) { var val=request.responseText; document.getElementById("dharmesh").innerHTML=val; } } </script><br /> </head><br /> <body></p> <h1>Ajax Demo</h1> <form name="form"> Enter id:<input type="text" name="t1" onkeyup="sendInfo()"><br /> </form> <p> <span id="dharmesh"></span><br /> </body><br /> </html><br />

Process.jsp

<%@ page import="java.sql.*"%>  
<%@page contentType="text/html" pageEncoding="UTF-8"%>


    
        
        JSP Page
    
    
        <%
            String s=request.getParameter("val");
            if(s==null||s.trim().equals(""))
            {
                out.println("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","");
                    PreparedStatement ps=con.prepareStatement("select * from emp where id=?");
                    ps.setInt(1, id);
                    ResultSet rs=ps.executeQuery();
                    while(rs.next())
                    {
                        out.println(rs.getInt(1)+" "+rs.getString(2));
                    }
                }
                catch(Exception e)
                {
                    out.println(e);
                }
            }
        %>