Magazine
 
Quick Review:Ajax
 
Ajax Examples
 

The above html page has input text field of id “search” with “onkeyup” attribute that is set to the JavaScript function “searchText ()”. This method is called each time the user releases the key up. This input text component also has an attribute “autocomplete” which is set to the value “off”. This attribute is used to turn on/off the default behavior of text field to show texts entered before. But here we have to show matched data from the database. So it is necessary to set this attribute to ‘off’.

searchText ()” first tries to get HTTP request object maintaining the browser compatibility. In this example, this object is stored in the variable named “xmlHttp”.Read how to get HTTP request object on page 12

Next step is to determine which method should be invoked after getting the response from the server. In this example, the method “callback ()” is assigned for this purpose. Now the request for servlet “AJAXSearchServlet” is forwarded to the server along with search keyword as parameter.

AJAXSearchServlet.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.*;
public class AJAXSearchServlet extends HttpServlet {
public void doGet( HttpServletRequest request, HttpServletResponse response ) throws
ServletException, IOException {
String search = request.getParameter(“search”);
response.setContentType(“text/html”);
response.setHeader(“Cache-Control”, “no-cache”);
if(!((search.trim()).equals(“”))){
String searchString = getSearchResult(search);
System.out.println(searchString);
response.getWriter().write(searchString);
}
else{
System.out.println(“Length of string”+(“”.length()));
response.getWriter().write(“”);
}
}
public String getSearchResult(String search) {
Connection con = null;
String url = “jdbc:mysql://192.168.10.59:3306/”;
String db = “javajazzup”;
String driver = “com.mysql.jdbc.Driver”;
String user = “root”;
String pass = “root”;
String finalSearch=””;
try{

Apr 2008 | Java Jazz Up |38
 
previous
index
next
 
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,

30
, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 , 54, 55, 56, 57,

58
, 59, 60, 61, 62, 63 , 64, 65 , 66 , 67 , 68 , 69 , 70, 71, 72, 73, 74, 75, 76, 77, 78,   Download PDF