Sanjana
Sanjana

Reputation: 467

Create dynamic table using AJAX and JSP

I have a HTMl form which has a datepicker field. I am using AJAX to send this parameter to JSP where it compares this date with the database. If the match is found , it should dynamically create rows and print table date.

My question is where should I put the code of table creation -inside JSP or in AJAX using DOM.

I tried to do it using AJAX, but responseText is returning me a string separated by space.So I thought of using split and iterating through the array and creating elements dynamically. It is not working.

function fetch()
{
    alert("sadasd");
    var c= new XMLHttpRequest();

    c.onreadystatechange= function()
    {
        if(c.readyState==4)
        {
            var text=c.responseText;
        }
    }

    c.open("GET","serv.jsp?filter="+document.getElementById("datepicker").value,true);
    c.send();
    x=text.split(" ");
    //document.write(x[1]);
}    

Serv.jsp

<%@page import="java.sql.*" %>
<% 
    try {
        Class.forName("com.mysql.jdbc.Driver");
        java.text.SimpleDateFormat st = new java.text.SimpleDateFormat("MM/dd/yyyy");
        java.util.Date utilDate = st.parse(request.getParameter("filter"));
        java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

        java.sql.Connection con = java.sql.DriverManager.getConnection("jdbc:mysql://localhost:3306/ankur", "root", "root");
        PreparedStatement stm = con.prepareStatement("select * from employee");
        ResultSet rs = stm.executeQuery();

        while (rs.next()) {
            if (rs.getDate(3).equals(sqlDate)) {
                out.println(rs.getString(1));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }    
%>

Upvotes: 0

Views: 1766

Answers (1)

user243405
user243405

Reputation: 83

For print table you can use the HTML tag in your jsp page

like

 while(rs.next())
    {if(rs.getDate(3).equals(sqlDate))
    {
          String sql = "<table><tr><td>"+rs.getString(1)+"</table></tr></td>";   
    }
    }}

or for batter use of ajax you can use this link

Upvotes: 1

Related Questions