0

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();
    }    
%>
Tiny
  • 27,221
  • 105
  • 339
  • 599
Sanjana
  • 467
  • 2
  • 8
  • 20
  • No scriptlets please. See [How to avoid Java Code in JSP-Files?](http://stackoverflow.com/q/3177733/1031945) – Aniket Kulkarni Feb 05 '14 at 05:38
  • You may want to use jQuery AJAX and avoid Scriptlets. – Tiny Feb 05 '14 at 05:41
  • ur jsp code "out.println(rs.getString(1));" prints a new line, and not a space. hence ur split code isn't working. u may try this "out.print(rs.getString(1) + ", ");" a CSV output and in ur js split it using "," –  Feb 05 '14 at 05:41

1 Answers1

1

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

user243405
  • 83
  • 7