Java Script & Ajax




How does "google search suggester"  works ?


How does google search works ? Here i am not explaining how does actual google works , but i am explaining how google search suggester works.


This may not the exact google search suggester but this example works like google search suggester.
I have taken some test data with the map as display value would be key and link would be value from the has map.


Test data -- static data from the servlet
-----------

JAXB
Exceptions
String
Design Pattern
Java Script
Java Advance Utils

if we search with above starting letter then as a result we will get the link as given below.

modified search








































googeHomePage.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Google Search Simulator</title>
</head>
<script type="text/javascript">
var xmlHTTP;
function hideDiv(){   //create browser object and hide div
document.getElementById("resultText").style.visibility="hidden";
if(window.XMLHttpRequest){
xmlHTTP = new XMLHttpRequest();// IE7+ and Chrome,mozilla, Safari etc
}else{
xmlHTTP = new ActiveXObject("Microsoft.XMLHTTP"); // IE6,IE5
alert("IE object created");
}
}
function initXmlHTTP(){
//alert(" inside xml HTTP ");

var enteredText = document.getElementById("enteredtextvalue").value;

//alert("enteredText:"+enteredText);
xmlHTTP.open("GET", "MyGoogleSearhSevlet?enteredText="+enteredText, true);
xmlHTTP.send();
xmlHTTP.onreadystatechange = makeCallToServer;//call back in Ajax
}
function makeCallToServer(){
if(xmlHTTP.readyState==4){
if(xmlHTTP.status==200){   //data received from server
//alert("response successfully received from server");
//alert("res:"+xmlHTTP.responseText);

//alert("response successfully received from server");
//alert(xmlHTTP.responseText);
//alert(xmlHTTP.responseText.length);
    //data will be populate in div
if(xmlHTTP.responseText!=null && xmlHTTP.responseText.length>0){
document.getElementById("resultText").style.visibility="visible";
document.getElementById("resultText").innerHTML = xmlHTTP.responseText;
}else{
      //if received data is null hide the div
document.getElementById("resultText").style.visibility="hidden";
}
   }
}
}

</script>
<body onload="hideDiv();">
<div style="width: 513px;" align="center">
<img alt="google" src="logo3w.png">

</div>
<div id="enterTextDiv">
<input type="text" id="enteredtextvalue" style="width: 543px; " onkeyup="initXmlHTTP();">

</div>
<div id="resultText">

</div>
<div style="width: 513px; " align="center">
<input type="button" value="Google Search">
<input type="button" value="I'm Feeling Lucky">
</div>

</body>
</html>


---
MyGoogleSearhSevlet.java


package com;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Servlet implementation class MyGoogleSearhSevlet
 */
public class MyGoogleSearhSevlet extends HttpServlet {
private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MyGoogleSearhSevlet() {
   
        super();
        // TODO Auto-generated constructor stub
        System.out.println("my servlet....");
    }


/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = null;
String str="";
 // Get the value from browser
String enteredText = request.getParameter("enteredText");
StringBuffer buffer = new StringBuffer();
System.out.println(enteredText+"::"+enteredText.length());
  // test data from in the hash map, user can search with the keys and value will be link
Map map = new HashMap();
map.put("JAXB","http://suneel-javautils.blogspot.com/p/jaxb.html");
map.put("Exceptions","http://suneel-javautils.blogspot.com/p/all-exceptions-in-real-time.html");
map.put("String","http://suneel-javautils.blogspot.com/p/string-date-utils.html");
map.put("DesignPattern","http://suneel-javautils.blogspot.com/p/collection-framework.html");
map.put("Java Script","http://suneel-javautils.blogspot.com/p/java-script-utils.html");
map.put("Java Advance Utils","http://suneel-javautils.blogspot.com/p/java-advanced-utils.html");

if(enteredText!=null && enteredText.length()>0){
out = response.getWriter();
// preparing dynamic table of rows with the map data
Object topicArr[] = map.keySet().toArray();
buffer.append("<table>");
for(int i=0;i<topicArr.length;i++){
if(topicArr[i].toString().toLowerCase().startsWith(enteredText.toLowerCase())){
buffer.append("<tr>");
buffer.append("<td>");
buffer.append("<a href="+map.get(topicArr[i])+">"+topicArr[i]);
buffer.append("</a>");
buffer.append("</td>");
buffer.append("</tr>");
}
}
buffer.append("</table>");
System.out.println(buffer.toString());
   //adding result table to the response object
out.println(buffer.toString());
}else{
out = response.getWriter();
out.println(str);
}
}


/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}


}



























How to get Drop down "Display" Value


In web applications we deal with the drop downs . It is very easy to get the selected drop down value using java script , but getting the display value is bit tricky .  Here is the code snippet which tells about how to get the display value from the drop down..






Here is the java script code 
--------------------------------



<html>
<script type="text/javascript">
function getText(){
var drop = document.getElementById("mydropDown");
var selectedValue = drop.options[drop.selectedIndex].value;
alert("selectedValue:"+selectedValue);
var textValue = document.getElementById("mydropDown")[document.getElementById("mydropDown").selectedIndex].innerHTML;
alert("display Value:"+textValue);

}


</script>
<body>
<form name="myForm">
<select id="mydropDown">
<option value="one">oneText</option>
<option value="two">twoText</option>
<option value="three">threeText</option>
<option value="four">fourText</option>
</select>
<input type="button" value="getDisplayValue" onClick="return getText();">

</form>
</body>
</html>


How to Validate Text box with Special Characters


We might have seen lot of login pages with the special characters are not allowing. Some of the registration pages or some of the Password field force us to enter some special characters. In that type scenarios we need to validate the fields what user has entered.


We can achieve this by using the javascript regular expressions.
special characters : [/<>~`@%!#$^&+={}|<?};:()\'"]


Here is the login page with the username validation , the criteria is in the username field we should not allow the special character what i have already defined above .










here is java script code
----------------------------

<html>
<script type="text/javascript">
function validateUserName(){
var paramVal= document.getElementById('username').value;
var re = new RegExp('[/<>~`@%!#$^&+={}|<?};:()\"]');
var re1 = new RegExp("[\\[\\]']");
var message="Error .. do not enter special character at position:"+paramVal.search(re);
//alert(paramVal.search(re));
if (paramVal.match(re)) {
alert(message);
return false;
 } else if(paramVal.match(re1)){
alert(message);
return false;
}
return true;
 }
</script>
<body>
<form name="myForm" action="dropdown.html">
<table width="300px" height="150px">
<tr>
<td>
User Name :  
</td>
<td>
<input type="text" id="username">
</td>
</tr>
<tr>
<td>
Password:
</td>
<td>
<input type="password" id="password">
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="button" value="validate" onClick="return validateUserName();">
</td>
</tr>
</table>
</form>
</body>
</html>





How to add dynamic options to select box


Here is the code to add dynamic options (display value and actual value) to select box.
This type of code snippet may be useful 



<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<script type="text/javascript">
function addOptions(){
var myString = "zero,one,two,three,four";


var mySplitResult = myString.split(",");
var optionId = document.getElementById("newOption");
for(i=optionId.length;i<mySplitResult.length; i++){
optionId.options[i] = new Option(mySplitResult[i-1],mySplitResult[i-1]);
}
}
</script>
<body onload="addOptions();">
<form>
<select id="newOption">
<option value="select">select</option>
</select>
</form>
</body>
</html>



The first option "select" and the dynamically added options through the java script are 
"zero","one","two" and "three"..
These are the options added through the java script