Cheap VPS & Xen Server


Residential Proxy Network - Hourly & Monthly Packages

AJAX 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:

  1. load the org.json.jar file
  2. create input page to receive any text or number
  3. create server side page to process the request

Load the org.json.jar file

download this example, we have included the org.json.jar file inside the WEB-INF/lib directory.


create input page to receive any text or number

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

  1. <html>
  2. <head>
  3. <script>
  4. var request;
  5. function sendInfo()
  6. {
  7. var v=document.vinform.t1.value;
  8. var url=“index.jsp?val=”+v;
  9. if(window.XMLHttpRequest){
  10. request=new XMLHttpRequest();
  11. }
  12. else if(window.ActiveXObject){
  13. request=new ActiveXObject(“Microsoft.XMLHTTP”);
  14. }
  15. try{
  16. request.onreadystatechange=getInfo;
  17. request.open(“GET”,url,true);
  18. request.send();
  19. }catch(e){alert(“Unable to connect to server”);}
  20. }
  21. function getInfo(){
  22. if(request.readyState==4){
  23. var val=request.responseText;
  24. document.getElementById(‘amit’).innerHTML=val;
  25. }
  26. }
  27. </script>
  28. </head>
  29. <body>
  30.     <marquee><h1>This is an example of ajax</h1></marquee>
  31. <form name=“vinform”>
  32. Enter id:<input type=“text” name=“t1” onkeyup=“sendInfo()”>
  33. </form>
  34. <span id=“amit”> </span>
  35. </body>
  36. </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

  1. <%@ page import=“java.sql.*”%>
  2. <%
  3. String s=request.getParameter(“val”);
  4. if(s==null || s.trim().equals(“”)){
  5. out.print(“Please enter id”);
  6. }else{
  7. int id=Integer.parseInt(s);
  8. out.print(id);
  9. try{
  10. Class.forName(“com.mysql.jdbc.Driver”);
  11. Connection con=DriverManager.getConnection(“jdbc:mysql://localhost:3306/mdb”,”root”,”root”);
  12. PreparedStatement ps=con.prepareStatement(“select * from emp where id=?”);
  13. ps.setInt(1,id);
  14. ResultSet rs=ps.executeQuery();
  15. while(rs.next()){
  16. out.print(rs.getInt(1)+” “+rs.getString(2));
  17. }
  18. con.close();
  19. }catch(Exception e){e.printStackTrace();}
  20. }
  21. %>

download this ajax example

Output

ajaxexampledboutput1.jpg

ajaxexampledboutput2.jpg

Comments

comments