I want to refresh a jsp without flickering for every 5 seconds using ajax.This jsp is responsible to get the new records from the database and display the records in the form of a table. I don't know how to use ajax. Please send me one example for the same. Please help me. Please send your answer to.
1)ajax.jsp:
<%@page import="java.sql.*"%> <META HTTP-EQUIV="Refresh" CONTENT="5"> <html> <head> <script type="text/javascript"> function showData(){ xmlHttp=GetXmlHttpObject() var url="getdata.jsp"; xmlHttp.onreadystatechange=stateChanged xmlHttp.open("GET",url,true) xmlHttp.send(null) } function stateChanged(){ if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ document.getElementById("tab").innerHTML=xmlHttp.responseText; } } function GetXmlHttpObject(){ var xmlHttp=null; try{ xmlHttp=new XMLHttpRequest(); } catch(e){ try{ xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch(e){ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; } </script> </head> <body onload="showData();"> <table id="tab"> </table> </body> </html>
2)getdata.jsp:
<%@ page import="java.sql.*" %> <% String buffer="<table id='tab' border='1' >"; try{ Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("Select * from employee"); while(rs.next()){ buffer=buffer+"<tr><td>"+rs.getString("name")+"</td><td>"+rs.getString("address")+"</td><td>"+rs.getString("contactNo")+"</td><td>"+rs.getString("email")+"</td></tr>"; } buffer=buffer+"</table>"; response.getWriter().println(buffer); System.out.println(buffer); } catch(Exception e){ System.out.println(e); } %>
Ads