Monday, 12 September 2016

Ajax search from MYSQL database example in JSP

Ajax is used to get data dynamically by just pressing key. This example is the demonstration of getting data from database by just typing characters in textfield. In ajax you don't need to press submit button to get data. I assume that you have made MySQL database.

Now create a form that contains textfield.

search.html

To type something to be searched

<form name="vinform"  method="get" >
<input type="search" name="t1" size="80" placeholder="Type to search" onKeyUp="sendInfo()" class="textfieldsearch" style="height:35px;" autofocus>
</form>

To show data on this page add

<span id="arvind"> </span>

Include javascript code given bellow to this file

<script>
var request;
function sendInfo()
{
               var v=document.vinform.t1.value;
               var url="search.jsp?val="+v;

              if(window.XMLHttpRequest){
             request=new XMLHttpRequest();
             }
             else if(window.ActiveXObject){
             request=new ActiveXObject("Microsoft.XMLHTTP");
             }
             try
            {
              request.onreadystatechange=getInfo;
              request.open("GET",url,true);
              request.send();
             }
             catch(e)
            {
               alert("Unable to connect to server");
           }
}

function getInfo(){
          if(request.readyState==4){
          var val=request.responseText;
           document.getElementById('arvind').innerHTML=val;
           }
}
</script>


Now on search.jsp page write

search.jsp

<%@ page import="java.sql.*"%>

<%
String s=request.getParameter("val");
if(s==null || s.trim().equals("")){
out.print("Please Type anything to search");

}else{
out.println("<img src='ajax-loader.gif' alt='Searching'></img>");

String search=s;


try{

Statement stmt=null;
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/itcentre","root","aarvindd");

stmt = con.createStatement();
String sql="select * from table where cl_name like '%"+search+"%' " ;
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
out.println(rs.getString(1));
       out.println(rs.getString(2));

       }
rs.close();
stmt.close();
con.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}


%>

No comments:

Post a Comment

Change image source dynamically on hyperlink

 Changing image source dynamically using JQuery. Here in this example I have created there hyperlink and stored all images in the same folde...