step 1:
Create HTML page as shown below.
<html>
<head>
</head>
<body >
<table id="tab">
<tr>
<th>id</th>
<th>name</th>
<th>place</th>
</tr>
</table>
</body>
</html>
step 2: Create ajax function to fetch table content in database and call this function on loading of the page using window.onload as shown below.
window.onload= fetchrow()
function fetchrow() {
var data = 'tabledata=tabledata';
$.ajax({
type: "POST",
url: "Handler2",
dataType: "json",
data: data,
success: function (data)
{
if (data.dataarray) {
$.each(data.dataarray, function (key, value) {
var id = value.id;
var name = value.name;
var place = value.place;
var gender = value.gender;
var delete1 = value.delete;
$("#tab").append("<tr class='txt1'> <td>" + id + "</td><td> " + name + "</td><td>" + place + "</td> <td>" + gender + "</td></tr>");
});
}
}
});
}
window.onload()- by using this function we will call ajax on loading of the page.
In ajax call we use type as post and url is Handler2 this is servlet which acts as the interface between the database and ajax.
data in success function is json object which is return by the handler it contains json array(data.dataarray) this array contains data of each row of the table which we append to the table using $.each() function as shown above.
Handler2.java
JSONObject myjson = new JSONObject();
JSONArray array = new JSONArray();
try (PrintWriter out = response.getWriter())
{
if (request.getParameter("tabledata") != null)
{
DAO dao = new DAO();
HelperBean result = dao.FetchTableContent();
for (int i = 0; i < result.getformlist().size(); i++)
{
JSONObject json = new JSONObject();
formbean f1 = result.getformlist().get(i);
json.put("id", f1.getid());
json.put("name", f1.getname());
json.put("place", f1.getplace());
array.put(json);
}
myjson.put("dataarray", array);
out.print(myjson);
}
}
DAO is the class containg connection to the database it contains method (FetchTableContent) which returns arraylist of the object formbean which is stored in result.
formbean is a class containing id name and place.
add this object data to json array as shown above.
DAO.java
public HelperBean FetchTableContent( )
{ HelperBean h1=new HelperBean();
int status = 0;
try {
Statement st = (Statement) con.createStatement();
ResultSet rs = null;
rs = st.executeQuery("select * from tab2");
while (rs.next()) {
formbean f2 = new formbean();
f2.setid(rs.getInt("id"));
f2.setname(rs.getString("name"));
f2.setplace(rs.getString("place"));
h1.getformlist().add(f2);
}
} catch (Exception e) {
e.printStackTrace();
}
return h1;
}
this function fetches table content and stores it in helperbean and returns it to handler.