Page 1 of 1

AJAX Techniques - Google style text box Tutorial on a simple AJAX technique. Rate Topic: -----

#1 jrm402  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 51
  • View blog
  • Posts: 333
  • Joined: 18-March 10

Posted 12 April 2010 - 02:52 PM

In this tutorial, I will show you (not replicate) how Google uses AJAX to contact the server and populate the 'guess list' while typing to search.

Step one: First we need a simple html file named index.htm:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http: //www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title>Google-like AJAX feature</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>

<form action="" method="post">
	<p>Enter a month:</p>
	<p><input type="text" name="search" value="" class="text" /></p>
	<p id="response"></p>
	<p><input type="submit" name="submit" value="Submit" class="button" /></p>
</form>

</body>
</html>



Step two: Let's create our script tags in the head section of index.htm:
<head>
	<title>Google-like AJAX feature</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	
	<script type="text/javascript">
		<!-- AJAX code here.
	</script>
</head>



Step three: We're going to start populating our script tags in the head section now. The first thing we will do is set up the onkeyup event on the text box:
<p><input type="text" name="search" value="" class="text" onkeyup="showMonth(this.value);" /></p>


Now we can add the showMonth function in our script tags:
// Declare the function that will run when the user
// lets up a key.
function showMonth(text) {

}



Step four: So now when a user types in the textbox, every time they let up a key Javascript will call the showMonth function and send the value of the textbox as variable text. Our next step is to check and set our AJAX http request variable:
// Declare our request variable.
var request = null;
		
// Declare our function for setting the AJAX
// XMLHttpRequest to variable request.
function setAJAX() {
	// Set request variable for most modern
	// browsers.
	if(window.XMLHttpRequest)
	{
		request = new XMLHttpRequest();
		return true;
	}
	// Set request variable for older IE versions.
	else if(window.ActiveXObject)
	{
		request =  new ActiveXObject("Microsoft.XMLHTTP");
		return true;
	}
	// Return false if we cannot set the request
	// variable.
	else {
		return false;
	}
}


The first part declares the global variable request so we can use it across multiple functions. The function setAJAX() checks to see if the users browser can set the http request variable. If it can it sets request, if it can't it returns false.

Now that our setAJAX function is up, let's actually run the check. We're going to move back to the showMonth(); function:
if(setAJAX()) {
	
}
// Alert the user that we cannot do AJAX in their
// browser.
else {
	alert('Your browser does not support ajax');
}


So, if setAJAX doesn't return false, we have set the request variable and are ready to go. If it does return false, alert the user that their browser doesn't support AJAX.

Step five: Now we're going to actually do the AJAX part. We're going to populate the showMonth() function as follows:
function showMonth(text) {
	// Check to see if the request variable can be
	// set and set it.
	if(setAJAX()) {
		// Set our url to 'ajax.php?s=search_string'.
		var url = "ajax.php?s=" + text;
		
		// Set the onreadystatechange to find function
		// getData when ready.
		request.onreadystatechange = getData;
		
		// Open and send the request.
		request.open("GET", url, true);
		request.send(null);
	}
	// Alert the user that we cannot do AJAX in their
	// browser.
	else {
		alert('Your browser does not support ajax');
	}
}


First we set the url to call the php file we will create in step eight. The url includes the text that we are trying to search that we typed in our textbox. Next, we tell the browser that when AJAX is ready, call the getData function to continue processing the AJAX request. We then open and send the AJAX request to the server.

Step six: Let's make the getData function:
// Retrieve and output the data when it is ready.
function getData() {
	if(request.readyState == 4 && request.status == 200) {
		document.getElementById("response").innerHTML = request.responseText;
	}
}


All this function checks is if AJAX is ready and has provided a response. if it has, we set our response inside of <div id="response"></div>.

Step eight: Create a file called ajax.php and set it up as follows:
<?php

// Get the variable that we sent.
$str = $_GET['s'];

// Declare the array filled with months and
// an empty array where we can store months
// that match our search query.
$months = array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
$months_match = array();

?>


First, we get the string that we sent in the url. Next we set up an array filled with the months. Then, we declare $months_match which is an empty array that we will fill with months that match our query.

Step nine: Now we can perform our check to display the months that match our search query:
if(strlen($str)) {

}


First, check to see if our search string has a length to it meaning someone typed something.

// Set a counter variable for outputting.
$count = 0;


Next, store the $count variable. The $count variable is going to be the number of entries we found in the $months array that match our search string.

// Run a loop through all of the $months array.
// We will check each spot for a match.
for($i = 0; $i < count($months); $i++) {
	// If our search string is inside of $months[$i] and the
	// position of our search string is at 0 then proceed.
	if(stristr($months[$i], $str) && strpos($months[$i], $str) == 0) {
		// Add the matched month to the next spot in
		// $months_match array.
		$months_match[] = $months[$i];
		$count++;
	}
}


The code explains this step pretty well. stristr checks if $str is inside of $months[$i]. The only problem with this is that it will return true if the string is found at the end of the string. Example:
$str = "ber";
$months[$i] = "December";

// stristr($months[$i], $str) will return true;


To fix this we check to make sure $str is at the beginning of $months[$i] by using stripos.

Now we need to output:
// Now we need to loop through our $months_match
// array and output each spot.
for($i = 0; $i < count($months_match); $i++) {
	echo $months_match[$i];
	// If we just outputted the last spot in the
	// array, then don't output a line break - 
	// it is not needed after the last spot.
	if($i != (count($months_match) - 1)) {
		echo "<br />";
	}
}


The code is self-explanatory.

The last step is to check if we didn't have any results. The [inline]$count variable will still be 0 if we didn't:
// If we didn't find anything that matched our
// search query, then output 'None found'.
if($count == 0) {
	echo "<b>None found</b>";
}



And that's that, open the index.htm on a server (or from localhost) and watch it work.

Here is the two files in full:

index.htm
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http: //www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title>Google-like AJAX feature</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	
	<script type="text/javascript">
		// Declare our request variable.
		var request = null;
		
		// Declare our function for setting the AJAX
		// XMLHttpRequest to variable request.
		function setAJAX() {
			// Set request variable for most modern
			// browsers.
			if(window.XMLHttpRequest)
			{
				request = new XMLHttpRequest();
				return true;
			}
			// Set request variable for older IE versions.
			else if(window.ActiveXObject)
			{
				request =  new ActiveXObject("Microsoft.XMLHTTP");
				return true;
			}
			// Return false if we cannot set the request
			// variable.
			else {
				return false;
			}
		}
		
		// Declare the function that will run when the user
		// lets up a key.
		function showMonth(text) {
			// Check to see if the request variable can be
			// set and set it.
			if(setAJAX()) {
				// Set our url to 'ajax.php?s=search_string'.
				var url = "ajax.php?s=" + text;
				
				// Set the onreadystatechange to find function
				// getData when ready.
				request.onreadystatechange = getData;
				
				// Open and send the request.
				request.open("GET", url, true);
				request.send(null);
			}
			// Alert the user that we cannot do AJAX in their
			// browser.
			else {
				alert('Your browser does not support ajax');
			}
		}
		
		// Retrieve and output the data when it is ready.
		function getData() {
			if(request.readyState == 4 && request.status == 200) {
				document.getElementById("response").innerHTML = request.responseText;
			}
		}
	</script>
</head>
<body>

<form action="" method="post">
	<p>Enter a month:</p>
	<p><input type="text" name="search" value="" class="text" onkeyup="showMonth(this.value);" /></p>
	<p id="response"></p>
	<p><input type="submit" name="submit" value="Submit" class="button" /></p>
</form>

</body>
</html>



ajax.php
<?php

// Get the variable that we sent.
$str = $_GET['s'];

// Declare the array filled with months and
// an empty array where we can store months
// that match our search query.
$months = array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
$months_match = array();

if(strlen($str)) {
	// Set a counter variable for outputting.
	$count = 0;
	
	// Run a loop through all of the $months array.
	// We will check each spot for a match.
	for($i = 0; $i < count($months); $i++) {
		// If our search string is inside of $months[$i] and the
		// position of our search string is at 0 then proceed.
		if(stristr($months[$i], $str) && strpos($months[$i], $str) == 0) {
			// Add the matched month to the next spot in
			// $months_match array.
			$months_match[] = $months[$i];
			$count++;
		}
	}
	
	// Now we need to loop through our $months_match
	// array and output each spot.
	for($i = 0; $i < count($months_match); $i++) {
		echo $months_match[$i];
		// If we just outputted the last spot in the
		// array, then don't output a line break - 
		// it is not needed after the last spot.
		if($i != (count($months_match) - 1)) {
			echo "<br />";
		}
	}
	
	// If we didn't find anything that matched our
	// search query, then output 'None found'.
	if($count == 0) {
		echo "<b>None found</b>";
	}
}

?>



Is This A Good Question/Topic? 3
  • +

Replies To: AJAX Techniques - Google style text box

#2 josemayi  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 22
  • Joined: 25-January 10

Posted 29 July 2010 - 03:55 PM

great job! it was really helpful. I was trying to learn some basic AJAX from a book, and I spend an entire day trying to fix the code because it wasn't working. When I tried your example it worked perfectly. Keep up the good work!
Was This Post Helpful? 0
  • +
  • -

#3 vladqui  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 17-July 12

Posted 17 July 2012 - 02:38 PM

Wonderful tutorial JRM.
Just a pair of tweaks and I had it working on my search engine.
Thanks..!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1