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($chCURLOPT_URL$url);
    
curl_setopt($chCURLOPT_RETURNTRANSFER1);
    
curl_setopt($chCURLOPT_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 &quot;<?php echo @$_GET['q']; ?>&quot;</h2>

        <ol<?php echo @$_GET['start'] > ' 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']; ?>&amp;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).


Rate It


Bookmark It

  • del.icio.us
  • Digg
  • Furl
  • Google
  • Technorati
  • Ma.gnolia
  • BlinkList
  • Blogmarks
  • Rojo
  • StumbleUpon

Comments

8 comments so far, why don't you post one too?

Link Manager

Wednesday, June 25, 2008 | View all comments by Link Manager

Sorry, but your demo link gives me an error / script error!

Andreas

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).

Nils Hendriks

Wednesday, August 13, 2008 | View all comments by Nils Hendriks

Hi, I get the same error :-(

"Fatal error: Call to undefined function curl_init()"...

Kevin

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 "â

Firefox Hater

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

Andreas

Tuesday, November 25, 2008 | View all comments by Andreas

@Firefox Hater - Hehe ok.

middle east post

Sunday, December 28, 2008 | View all comments by middle east post

thank you

middle east post

Sunday, December 28, 2008 | View all comments by middle east post

do you think its safe to use adsense in this script ?


Comments closed

Comments are closed



Post It

From June 02 to April 23

  1. Mogrify is what you're looking for if you want to convert multiple images to multiple other images in ImageMagick
  2. Tommorrow, finally, the inFamous demo will be friggin availble on PSN!! Suweeeeeeeeet
  3. Fuck canvas is cool, I've started playing around with old 3D-shit again :)

September 2010

S M T W T F S
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


Recent Comments

  1. Vlad on A follow-up to "An alternative to div overlays":
    I'll try this.....
  2. Steve on jQuery Live Ajax Search Plug-in:
    This is a great script but I've got...
  3. Frank on jQuery Live Ajax Search Plug-in:
    Hey, sounds like a great plugin! I ...
  4. Andreas on jQuery Drag to Select Plug-in:
    @Paul - I didn't take into account ...

Style Switcher

The style switcher allows you to change the look and feel of exscale.se.
Only CSS and JavaScript are changed. The XHTML stays the same.

For more information about the styles, check the styles page.


Categories


Random Quote

Kommer alla vara där eller kommer tex Scott vara hemma? - Boode


Random Images




Answer This!

Do you find the "scroll-pagination" annoying? (If you don't know what it is, scroll to the bottom of the first-page)


Blog Roll