Live ajax search using the Google search API
Published Monday, May 19, 2008 in Ajax, Javascript, jQuery, PHP, Progressive Enhancement, Usability
I realized the bogus-search-results script from Live Ajax Search jQuery Plug-in may not have been very satisfying to you visitors, so I thought I'd show you how to use the Google search API to create a real live ajax search on your site.
This example requires PHP and if you're running any version below 5.2 you'll need Michal Migurski's JSON-class as well.
The PHP (and HTML erm..)
The Google search API is basically just a URL you pass a search-query to and it returns a JSON with results.
I won't go in to too specific details about the API, if you wish to know more please refer to the documentation.
Create a search-results.php file and put the following code in it:
<?php
require_once 'JSON.php';
# Your site URL
$site = 'exscale.se';
# Make sure a search-query was entered
if(isset($_GET['q'])) {
# Are we on the first page?
$start = isset($_GET['start']) ? $_GET['start'] : 0;
# The URL to the Google search API
$url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=' .urlencode($_GET['q']) .'%20site:' .$site .'&rsz=large&start=' .$start;
# Initiate CURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, 'http://' .$site);
$body = curl_exec($ch);
curl_close($ch);
# Decode the JSON returned (you need the JSON-class if json_decode is undefined)
$body = json_decode($body);
# Build array
$i = 0;
$search_results = array();
# Loop through all results
foreach($body->responseData->results as $r) {
$search_results['results'][$i]['title'] = $r->title;
$search_results['results'][$i]['url'] = $r->url;
$search_results['results'][$i]['content'] = $r->content;
$i++;
}
# Loop through all the pages of results
if(isset($body->responseData->cursor->pages)) {
foreach($body->responseData->cursor->pages as $p) {
$search_results['pages'][] = $p->start;
}
}
# Make sure some results were returned
if(isset($search_results['results'])) {
?>
<h2>Search results for "<?php echo @$_GET['q']; ?>"</h2>
<ol<?php echo @$_GET['start'] > 0 ? ' start="' .($_GET['start'] + 1) .'"' : '' ?>>
<?php foreach($search_results['results'] as $sr) { ?>
<li>
<h3><a href="<?php echo $sr['url']; ?>"><?php echo $sr['title']; ?></a></h3>
<p><?php echo $sr['content']; ?><br /><a href="<?php echo $sr['url']; ?>">Read more</a></p>
</li>
<?php } ?>
</ol>
<?php if(isset($search_results['pages'])) { ?>
<ul>
<?php $i = 0; foreach($search_results['pages'] as $p) { $i++; ?>
<li>
<?php if((!isset($_GET['start']) && $p == 0) || (@$_GET['start'] == $p)) { ?>
<strong><?php echo $i; ?></strong>
<?php } else { ?>
<a href="/search/?q=<?php echo @$_GET['q']; ?>&start=<?php echo $p; ?>"><?php echo $i; ?></a>
<?php } ?>
</li>
<?php } ?>
</ul>
<?php } ?>
<?php
}
else {
?>
<p><strong>Sorry, there were no results</strong></p>
<?php
}
}
?>
As the search-results.php-file doesn't contain any DOCTYPE, html, head or body-elements it is obviously not valid HTML. How you implement the search-results on your own site differs depending on what type of site-structure you've got set up. Regardless you should probably be able to figure it out.
If you do include some sort of head/foot-templates in the search-results make sure not to include them if it's an ajax-call (isset($SERVER['HTTPXREQUESTEDWITH'])).
I'm going to assume the search-results.php will be included from a search.php-file in the root of your site. So visiting /search.php would display the search-results (provided a query is set) along with whatever else your site consists of, but visiting just /search-results.php will only output the results.
The HTML form
Now all you need to do is set up a form that submits a get-request to search.php:
<form method="get" action="/search.php">
<p>
<label for="q">Search</label>
<input type="text" name="q" id="q" />
<input type="submit" value="Find" />
</p>
</form>
The Ajax-magic
And now hijax that form:
<script type="text/javascript" src="http://aframework.googlecode.com/svn/trunk/__core/Modules/Base/1-jquery-1.2.1.js"></script>
<script type="text/javascript" src="http://aframework.googlecode.com/svn/trunk/__core/Modules/Base/jquery.dimensions.js"></script>
<script type="text/javascript" src="http://aframework.googlecode.com/svn/trunk/__core/Modules/Base/jquery.liveSearch.js"></script>
<script type="text/javascript">
$('#q').liveSearch({ajaxURL: '/search-results.php?q='});
</script>
</body>
I've set up an example-page and you can also download the example-files.
Enjoy!
Woopsy
Seems curl_init isn't available from my host (bummer). The example should still work for you locally though,and hopefully live as well (unless you suffer from the same limitations).






Comments
8 comments so far, why don't you post one too?
Wednesday, June 25, 2008 | View all comments by Link Manager
Sorry, but your demo link gives me an error / script error!
Wednesday, June 25, 2008 | View all comments by Andreas
Hence:
Woopsy
Seems curl_init isn't available from my host (bummer). The example should still work for you locally though,and hopefully live as well (unless you suffer from the same limitations).
Wednesday, August 13, 2008 | View all comments by Nils Hendriks
Hi, I get the same error :-(
"Fatal error: Call to undefined function curl_init()"...
Wednesday, August 20, 2008 | View all comments by Kevin
Thanks for these great articles andreas, it's nice to get a full walk through of how to make it actually work (Google API).
I have it set up and everything seems to be working fine except for one detail. I seem to be having issues with character encoding. I have it set to UTF-8, and I still I see "â
Tuesday, November 25, 2008 | View all comments by Firefox Hater
Why should I use a "better" browser for newbie lambs like you. Firefox limits your browser behavior and all those "plugins" are pure extra hard work. What Firefox does with plugins were common features used by the IE shell Ace Web Surface ten years ago, but without the hassle and controlling behavior of Firefox
Tuesday, November 25, 2008 | View all comments by Andreas
@Firefox Hater - Hehe ok.
Sunday, December 28, 2008 | View all comments by middle east post
thank you
Sunday, December 28, 2008 | View all comments by middle east post
do you think its safe to use adsense in this script ?