Monday, 24 October 2016

Fetch Data From Database Using Java and Ajax


Hi friends, I think you all know how to fetch data from databse using Servlet, but some time you need to fetch data in another way like if insert into text and press the Enter key then data should me come into other text fields.

So I am giving example here. learn and enjoy this code

1.Jsp page

Here i have taken four input type text,
See Book Id,there is onKeyup property means when you enter into Book ID text and then press the Enter button then you will get data form database in to others fields.

onkeyup="get(this.value,<%=session.getAttribute("sid")%>)"

here this.value  means it will take enter value and ,<%=session.getAttribute("sid")%> means it will take id of your product, it is not necessary if your product is only one login

 <label class="text-danger"><strong>BOOK ID :</strong></label> <input type="text" name="lib_bookID"  id="lib_bookID"onkeyup="get(this.value,<%=session.getAttribute("sid")%>)" />
                    
                    
<label class="text-danger"><strong>AUTHOR NAME :</strong></label> <input type="text" style="color: green;"
name="lib_author" id="lib_author"/>
                          

<label class="text-danger"><strong>BOOK NAME :</strong></label> <input type="text" name="lib_book_name" id="lib_book_name"/>
                                                                                                             
<label class="text-danger"><strong>PUBLICATION NAME :</strong></label> <input type="text" name="publication_book" id="publication_book" />
                                               

2. Ajax


xmlhttp.open("GET","Getdata?book_number="+book_number + "&sid="+sid ,true);

see here, I have taken two parameter, because I have two login for different products.

And also check url ,this url must match with servlet url

<script>
       
        function get(book_number,sid)
               {
                   var xmlhttp=new XMLHttpRequest();
                   xmlhttp.onreadystatechange=function()
                     {
                     if (xmlhttp.readyState==4 && xmlhttp.status==200)
                       {
                       
 var responseArray = xmlhttp.responseText.split(",");
                         document.getElementById("lib_book_name").value=responseArray[0];
                         document.getElementById("lib_author").value=responseArray[1];
                         document.getElementById("publication_book").value=responseArray[2];
                       }
                     };
                    
                  
                   xmlhttp.open("GET","Getdata?book_number="+book_number + "&sid="+sid ,true);
                   xmlhttp.send();

               }
        </script>

3. Servlet code
package com.bookdetails;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.mail.Session;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dbActivity.JDBCUtil;
@WebServlet("/Getdata")
public class Getdata extends HttpServlet {
       private static final long serialVersionUID = 1L;
       public Getdata() {
              super();
                     }

      
       protected void doGet(HttpServletRequest request,
                     HttpServletResponse response) throws ServletException, IOException {
             
String book_number = request.getParameter("book_number");
String sid=request.getParameter("sid");
      
      

              System.out.println(book_number);
              System.out.println(sid);

              String book, auth, puslh;
              try {

                     Connection con = JDBCUtil.getConnection();
       // here create connection according to youJDBCUtil is my connection class

       
                     PreparedStatement ps = con
                                  .prepareStatement("SELECT BOOK_NAME,AUTHOR_NAME,PUBLISHER_NAME from BOOK_REGISTRATION where BOOK_NUMBER=? and SID=?");
                     ps.setString(1, book_number);
                     ps.setString(2, sid);
                     ResultSet rs = ps.executeQuery();
                     if (rs.next()) {
                           book = rs.getString("BOOK_NAME");
                           auth = rs.getString("AUTHOR_NAME");
                           puslh = rs.getString("PUBLISHER_NAME");
                     } else {
                           book = "";
                           auth = "";
                           puslh = "";
                     }
                     response.getWriter().write(book + "," + auth + "," + puslh);

                    
              } catch (Exception e) {

                     e.printStackTrace();
              }

       }

       protected void doPost(HttpServletRequest request,
                     HttpServletResponse response) throws ServletException, IOException {

       }

}

If any query then put your questions into comment box.

Thanks
Neeraj Srivastava

Happy Learning

No comments:

Post a Comment