How to get value from database without refreshing JSP page?

UPDATED: 04 July 2011
There are situations when you need data without refreshing current page. We can achieve this using jQuery or AJAX. Following example demonstrate it using jQuery.

test.html
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
        <script>
            $(document).ready(function(){
                 $("#users").change(function(){
                     var value = $(this).val();
                     $.get("data.jsp",{q:value},function(data){
                      $("#javaquery").html(data);
                     });
                 });
             });
        </script>
    </head>
    <body>
        <select id = "users">
           <option value="">Select Account ID</option>
           <option value="0">0</option>
           <option value="1">1</option>
        </select>
        <br />
        <div id="javaquery"><b>Name will be displayed here</b></div>
    </body>
</html>

data.jsp
<%
   String name = "";
   String q = request.getParameter("q");
   try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://x.x.x.x:3306/javaquery", "username", "password");
        Statement smt = con.createStatement(); //Create Statement to interact
        ResultSet r = smt.executeQuery("select * from users where(AccountID='" + q + "');");
        while (r.next()) {
          name = r.getString("name");
        }
        con.close
   } catch (Exception e) {
        e.printStackTrace();
   }
%>
Name:<%out.print(name);%>
Output:
jquery, ajax

jquery, ajax

0 comments :