Close

Log In

 
  Log In Password Forgot?

Not a member yet?

Sign Up Now

jQuery autocomplete

Google Autocompletion
Auto-completion of search terms is an AJAX feature popularized by Google that reduces typing by listing possible keywords as the user types.

This article will show you the steps of building a auto suggestion box with PHP and jQuery (No autocomplete Plugin or any other components are needed). We’re going to check what a user has typed in, make a query on goolge via PHP and pass the results back in a suggestion list, all via an AJAX call in jQuery. This is a very basic and comprehensible solution with only a few lines of code. All you need is a little HTML form, a server-sided PHP Script and a little jQuery Script for the AJAX request and the suggestion box creation.View Demo

Let’s start with the PHP Script

This script makes a query on google and returns data in a javascript object. Of course you can connect to a MySQL database at this point instead of query google. Save the file as google_autocompletion.php.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
header('Content-Type: text/plain; charset=utf-8');
$q = isset($_REQUEST['q']) ? $_REQUEST['q'] : '';
$url = "http://google.ch/complete/search?output=toolbar&q=%1";
$url = str_replace("%1",$q,$url);
 
$items = array();
$xml = simplexml_load_file($url,null,LIBXML_NOERROR|LIBXML_NOWARNING);
if($xml){
	foreach ($xml as $item) {
		array_push($items,($item->suggestion->attributes()->data));
	}
}
//return a javascript object
echo 'var result = {query:"'.$q.'",suggestions:["'.implode('","', $items).'"]};'

The JQuery

The jQuery is really the middle-man of the process, it’s going to handle all the front-end stuff. Save the file as script.js or copy it between the <head>-Tag of your html file.

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
$(function() {
	var q = $("#q");
	var d = $("<div></div>").addClass("container").css({width:q.outerWidth()-2,top:q.offset().top+q.outerHeight(),left:q.offset().left});
	d.hide();
	d.appendTo("body");
	var s=false;
	q.attr("autocomplete","off").keyup(function(e) {
		if(q.val().length==0){
			d.hide();
			s=false;
			return;
		}
 
		d.children().removeClass("selected");
		if (e.keyCode == 40){
			if(!s||s.next().length==0)
				s= d.children().first();
			else
				s = s.next();
 
			if(s.length>0)
				s.addClass("selected");
			return;
		}else if (e.keyCode == 38){
			if(!s||s.prev().length==0)
				s= d.children().last();
			else
				s = s.prev();
 
			if(s.length>0)
				s.addClass("selected");
			return;
		}else if(e.keyCode==13){
			window.location="http://www.google.com/search?q="+s.text();
		}
 
		$.ajax({ url: "google_autocompletion.php",type: "GET",data: "q="+q.val(),dataType: "script", success: function(data){
		var a = result.suggestions;
		d.empty().show();
 
		for(var i=0;i<a.length;i++);
                        var e=$("<span>"+a[i]+"</span>");
			e.hover(function(){
					s=$(this);
					s.addClass("selected");
				},function(){
					d.children().removeClass("selected");
				}).click(function(){
					window.location="http://www.google.com/search?q="+$(this).text();
				});
			d.append(e);
		}
		}});
	}).blur(function(){
		s=false;
		d.fadeOut("slow")
	});
});

The HTML form

Create a html file with a form and include the javascript above.

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
<html>
<head>
<style>
body {
  padding-top:100px;
  text-align:center;
}
.container{
  position:absolute;
  border:#000 solid 1px;
  text-align:left
}
.container span{
  display:block;
  background:#fff;
  color:#000
}
.container span.selected{
  background:#000;
  color:#fff
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script src="script.js" type="text/javascript"></script>
</head>
<body>
<h1>Google Search</h1>
<form method="get" id="sf" action="http://www.google.com/search">
  <input type="text" value="" name="q" id="q" size="30"/>
  <input type="submit" id="submit" value="Search" />
</form>
</body>
</html>
View Demo

Related Articles

Share this

The Author

admin - Hallo, ich bin 25 und ich bin ein Software- und Webentwickler. Meine Interessen decken alle Bereiche der Programmierung ab, einschliessend ASP, Python, JavaScript, AJAX, PHP, .NET, Java, C#, C++, Objectv-C, Flash, Cocoa, SQL, XML und alles dazwischen. www.simra.ch

Leave a Reply

 
© 2010 onYou GmbH. All Rights Reserved