I want to display the book name retrieved from database in the jsp page. Everything is working fine, but when the ajax
success is to be executed the each
function is doing the problem. It does not display anything. I checked everything behind and after it, all are working well even the data is retrieved and passed back to the ajax
as JSON object
but while iterating
something is going wrong. If in place of each function of jquery
i write any other alert function or simple text to display, it is working but not the each function. Where is the problem? Plz help me. Below is the code of my servlet
and jsp
page.
EbookSearchResult.java
response.setContentType("application/json;charset=UTF-8");
PrintWriter out = response.getWriter();
String search=request.getParameter("searchText");
String pattern="%"+search+"%";
ArrayList<String> result=new ArrayList<String>();
try{
Connectivity obj=new Connectivity();
obj.connect();
Statement stmt;
ResultSet rs;
stmt=obj.con.createStatement();
rs=stmt.executeQuery("select bookTitle from ebooks where bookTitle LIKE '"+pattern+"'");
if (!rs.next())
{
return;
}
while(rs.next()){
String str=rs.getString("bookTitle");
result.add(str);
}
String json = new Gson().toJson(result);
out.write(json);
}
catch(Exception e){
out.println(e.toString());
}
search.jsp
<script type="text/javascript">
$(document).ready(function()
{
$("#SearchButton").click(function()
{
var searchText = $("#search").val();
if(searchText.length > 3)
{
$("#searchResult").html("<img src='images/loading.gif'/>Checking availability...");
$.ajax({
// the URL for the request
url: "EbookSearchResult.do",
// the data to send (will be converted to a query string)
data: {
searchText: searchText
},
// whether this is a POST or GET request
type: "POST",
// the type of data we expect back
dataType : "json",
// code to run if the request succeeds;
// the response is passed to the function
success: function(json) {
$.each(json, function(index,value) {
$("#searchResult").append(value);
});
},
// code to run if the request fails; the raw request and
// status codes are passed to the function
error: function( xhr, status, errorThrown ) {
$("#searchResult").html("No Search Results found...");
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
}
});
}
else
{
$("#searchResult").html("Search Text should be atleast 4 character");
}
});
});
</script>