I am using Ajax to do a live search and all i want is the data t be displayed in a div called "results". However when im ding the search, it displays the search form again and then the results div. How do I go by solving this? Here is the ajax code:
function finding(str)
{
if (str.length==0)
{
document.getElementById("results").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("results").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","toy_search.jsp?query="+str,true);
xmlhttp.send();
}
I have added the search page here:
<%@page contentType="text/html" pageEncoding="UTF-8" import="java.sql.*, toyShop.*,java.util.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Toy Search</title>
<script type="text/javascript" src="js/search.js"></script>
</head>
<body>
<h2>Toy Search</h2>
Find toy: <input type="text" name="query" id="query" onkeyup="finding(this.value)" /><br>
<%
ToyManager toyM = new ToyManagerImp();
ArrayList<ToyData> toy_data = new ArrayList<ToyData>();
String toyName = null;
String toyBrand = null;
String desc = null;
if(!MySQLConn.getInstance().isConnected()){
MySQLConn.getInstance().connect();
}
if(request.getParameter("query") != null && !request.getParameter("query").equals("")){
String query = request.getParameter("query");
toy_data = toyM.searchToy(MySQLConn.getInstance(), query);
}
%>
<div id="results">
<%
if(toy_data != null && !toy_data.isEmpty()){
for(int i = 0; i < toy_data.size(); i++){%>
<%=toy_data.get(i).getToyName()%>
<%= "<br>"%>
<% }
}
%>
</div>
</body>
</html>