site search with the Google AJAX Search API

Google has replaced the AJAX Search API with Custom Search, so this no longer works. It’s kept here for posterity only.

ajax_search.js uses the Google AJAX Search API to do site search. It’s similar to Google’s existing site search, except that it shows the results within your site, not Google’s. It also degrades gracefully, by falling back to standard Google site search over HTTP for users who don’t have JavaScript.

You can check out the JavaScript, or try it out right now!

To use this on your site, first apply for an AJAX Search API key. Then, place ajax_search.js on your server and the following HTML on your page:

<form class="form" method="get" action="http://www.google.com/search"
  onsubmit="new site_search('[YOUR_DOMAIN]', q.value); return false;">
  <input type="hidden" name="sitesearch" value="[YOUR_DOMAIN]" />
  <input type="text" name="q" id="query" value="Search" />
</form>

<script type="text/javascript"
   src="http://www.google.com/uds/api?file=uds.js&v=1.0&key=[YOUR_KEY]">
</script>
<script type="text/javascript" src="[PATH]/ajax_search.js"></script>

Replace [YOUR_KEY], [YOUR_DOMAIN], and [PATH] with your AJAX Search API key, your site’s domain, and the path to ajax_search.js on your server, respectively.

Finally, set the results_id variable in ajax_search.js to the id of an existing div where you want search results to be placed. This div will be deleted and recreated when a search is performed. You can also customize results_header, results_footer, and searching_message, if you want.

The search results are placed in divs with distinct classes, so you can style them with CSS. Here are the classes:

gsc-title
gs-result
 |- gs-title
 |- gs-snippet
 |- gs-visibleUrl
 |- gs-watermark
gsc-branding
 |- gsc-branding-text
 |- gsc-branding-img-noclear

The AJAX Search API stylesheet has more details. As an example, here’s the CSS used on this site:

div.gs-result           { margin-top: 1em; }
div.gs-title            { text-decoration: underline; }
div.gs-visibleUrl       { color: green; }
div.gs-visibleUrl-short { display: none; }
div.gs-visibleUrl-long  { display: none; }
div.gs-watermark        { display: none; }

div.gs-snippet {
  font-size: .9em;
}

div.gs-snippet br { display: none; }

table.gsc-branding   {
  border: none;
  margin-top: 1em;
}
td.gsc-branding-text { color: gray; }
td.gsc-branding-img-noclear {
  padding-left: 2px;
  padding-top: 5px;
}
img.gsc-branding-img-noclear { margin-bottom: -3px; }

One final note: ajax_search.js doesn’t handle browser history or the back button. If you want the back button to work, consider setting window.location or window.location.hash, the current preferred approach.

Happy AJAX searching!

74 thoughts on “site search with the Google AJAX Search API

  1. The link doesn’t seem to work for me, neither on Firefox nor on IE. It only displays a “Searching…” comment. I guess the website has some deep secrets that I should not find!

  2. Mine just says ‘searching…’ too, not sure what I am doing wrong.

  3. hmm, odd. if you’re using firefox, could you pull up Tools=>Javascript Console, click Clear, then try searching again and see if it shows an error message?

  4. Hi Ryan. First of all, thanks for posting this code on your site, so helpful.  But, it is working in firefox but not in IE.  It says ‘the results are…’ then no results appear.  It also has an error on the page.  When I look at the details it points to line 58 of the javacript which says this ‘for (i = 0; i < results.length; i  ) ‘.  This is right before the ‘ugly brittle hack’.  I am just using, in the html, a div tag of <div id=”results”></div> where I renamed the id in the javascript.  I don’t understand why it is not working, Any ideas?  Thanks again.

  5. argh, sorry for the trouble, matt.

    IE is most likely getting confused because your div’s id and the results variable have the same name. try renaming your div to something else, like "search-results", and change the results_div_id at the top of ajax_search.js to match.

  6. That worked!  I don’t know why I didn’t realize what I had done.  Thanks again for the help, your code is awesome!!

  7. Ryan, this is a very cool and helpful tutorial. I have one ‘issue’ w/ putting it on my site. Below each result it says “clipped from Google – 11/2006” Anyway to get rid of that?

  8. Also, is there any way to hide the URL below the result summary so there’s just a link above?

  9. Instead of using a div tag to place the results, is there a way to put it in a table?  Thanks alot.

  10. if you’re ok with putting all of the search results in a single td cell, you could just put a div inside that cell. however, if you want each result in its own row in the table, you’ll need to write javascript to convert each div class="gs-result" into a tr.

  11. I know you can put a div in a td tag but it doesn’t seem to work when I do it with this.  I don’t know javascript well enough, so I’ll keep trying.  Thanks for the help.

  12. Hi Ryan, I’m impressed with the features in your code (particularly that results can be displayed within one’s site).  My primary question is How can I place the form in my top frame and target a page with the div in it in the bottom frame?  I’ve attempted to change the .setLinkTarget in the ajax_search.js to “main” (the name of my bottom frame) or even to “blank,” but it will not respond.  Can you offer some pointers on what I should specify in the form or the js file? 
      I have a test page that I’ve been experimenting with (http://nhmag.com/top-test.html) where I’ve placed the form in the position I would like it to be (the top of this page is to become a top frame) with the div lower on the same page, and I am getting some strange results.
      1.  Only a small portion of the documents containing any given work are displayed.  Entering “conservation,” for example, displays only 4 results.  Is there a limit setting on this?
      2.  The name of a given page is shown (it is an active link to the page), and below the text sample are two full repeated URLs , one which is plain text, the other appears to be a link but does not function.  Can these be removed or hidden?
      3.  And, like Larry above, I would also like to get rid of that “clipped from Google” link.  But the CSS link you gave goes only to a general CSS tutorial.  Is there a more specific link that shows how to hide parts of the search results? 
      Thanks for any advice you can offer.

  13. hi jim! thanks for the kind words.

    i don’t believe javascript in one frame can target the DOM in another frame. they’re two entirely separate DOMs. i’m no expert, though, so a recent reference on DHTML/javascript/DOM might prove me wrong.

    1. you can get up to 8 results for a search, but no more. this is a built-in limit, probably to prevent screen scraping. whether you actually get 8 results for a given search depends on what’s in google’s index.

    2 and 3. sure! you can do both of these with CSS. to hide the URLs, use:

    div.gs-visibleUrl { display: none; }
    div.gs-visibleUrl-long { display: none; }


    to hide the “clipped from Google” image, use:

    div.gs-watermark { display: none; }


    …but if you do, you’ll be violating the terms of service! see section 2.3, Attribution.

  14. I’d like to add the search box to the header of every page, but only have one page that shows the results of the search. Is there a way to do this? Excellent job BTW!

  15. you mean, you’d like search results to appear in a new HTML page, retrieved with a standard HTTP GET or POST instead of an AJAX request?

    sure, you could make the search box form submit to your search results page, and put an onLoad() in that page to trigger the actual AJAX search request. that’s clunky, though. :/

  16. Hello, I want to search on a mysql table when I m typing on a form
    What script does that ?

    Thankyou, verymuch !

  17. one question does this search sites that has not been indexed by google? or this will supposedly search the entire web?

  18. this only searches sites that have been indexed by google. if your site isn’t in google’s index, or if it’s an intranet, this won’t work for you.

    google does have intranet search solutions. they’re physical machines, though, and they cost money.

  19. Hi there

    I loved the code, I was searching for a way to use the google search without making users leave my website.

    Anyway, I think for usability is best to actually include de “Search” button, is there any way you can tell me how to do that?

    Thanks a lot.


    Felipe

  20. sure! just add a submit button to the form, e.g.
    <input type="submit" value="Search" /> </code>

  21. Hi again

    I’m a little confused with something, I think I did everything right but I keep getting “no results” everytime I search, I thought It was because I indexed the site on google almost at the same time but time passes by and still no results. Do you know if this is because of a badly implemented code or I just have to wait?

    Anyway, here goes my javascript code… sorry for the trouble


    <div class=”search”>
    <form class=”form” method=”get” action=”http://www.google.com/search”
      onsubmit=”new site_search(‘http://www.revistaasiatica.cl/’, q.value); return false;”>
      <input type=”hidden” name=”sitesearch” value=”http://www.revistaasiatica.cl/” />
      <input type=”text” name=”q” id=”query” value=”” />
      <input type=”submit” value=”Buscar” />
    </form>

    <script type=”text/javascript”
      src=”http://www.google.com/uds/api?file=uds.js&v=1.0&key=keygoeshere”>
    </script>
    <script type=”text/javascript” src=”../../permanent/ajax_search.js”></script>

    Didn’t know if it was necessary but I removed the key from the code

    Thanks


    Felipe

  22. hi felipe! try using just your domain, “revistaasiatica.cl”, without the “http://www.”, as the site_search() parameter and sitesearch input value.

  23. Hey,
    first of all thanks for this great script.
    I have some trouble though when I search a second time without reloading the page. It automatically switches to google.com and doesn’t stay on my site…
    Another problem is that it shows only a few results compared to the results that appear at googles original site. Is this on purpose  and is there any way to fix these two issues?

    And then, may I spread the results over more than one site? So that I only show about 4 results and to see the next four, the user has to click on a “next”-button that loads them dynamically into the divs… How could this work?

    I appreciate your help,
    thanks in advance,
    Andrea

  24. Me Again XD

    This has less to do with the coding, because as far as I can tell it’s working great (and I have to thank you for that really).

    Do you know how long it takes for google to update their err… database I guess, so it can show new results, because I put the search code in a test page first to see how it worked, but now everything is OK and it keeps giving me results like http://www.revistaasiatica.cl/test/x.html.

    I’m guessing it’s just a matter of time before it’s updated, but since you got the search box here, I thought I’d ask how long it takes.

    Thanks again, you’ve been great.


    Felipe

  25. I must say you are blog is the best, brother. I searched Google up and down can’t not find a simple example let alone tutorial. Then, I found your blog and I became the happiest programmer in the world. YAHOOOOOOOOOOOOOOO for snarfed.org.

  26. Hi, it’s me again. I am having problem with this search. It does return result but I can’t seem to position the result where I want it to appear. Your search result appears clean and neat within that box. I went through your site but can’t figure it out. Please, help.

  27. “sure, you could make the search box form submit to your search results page, and put an onLoad() in that page to trigger the actual AJAX search request. that’s clunky, though.”

    I really need this, but do not know how to implement it. Can you (Ryan) or some else please post the codes.

    Thanks

  28. hey,

    firebug and the JS console keep complaining about GwebSearch not being defined. I can’t find that function in either uds.js or ajax_search.js at all. I get the same results as  “Andrea, Tue 04 Sep 2007”: page goes to google.com after I hit enter in the search box (I defined the needed ID, etc.) WTH is this function? :)

  29. The GwebSearch class is part of Google AJAX Search’s public API. It’s used in ajax_search.js on line 36 to do the search. It’s defined in one of the other script files that uds.js pulls in.

    I took a look at the uds.js script tag on http://simonraven.kisikew.org/home/, and it looks like you have a couple &amp; sequences in the URL that shouldn’t be escaped. Try converting them to plain & characters.

  30. Ryan, this is brilliant – thanks! I’ve got it working really nicely.

    One question, though: I notice that Google have now increased the results returned to 32, with a pagination feature. How can I add that to your script?

    Thanks

  31. Many thanks for a fantastically quick response, Ryan. Unfortunately, when I replace the old script with this version, I get an error: Line 32, character 13, Expected identifier. Do I need to modify my page as well?

    Thanks

  32. hmm. it should be a drop-in replacement, so no, you shouldn’t have to modify your HTML.

    this site is currently using the new script, and it works for me in firefox 2. where do you see the error? which browser are you using?

  33. never mind, i see it in IE 6. ok, debugging… …fixed. whee, gotta love browser interoperability testing. thanks for catching that!

  34. hi dan! it looks like you have the same problem as simonraven, above. try changing the &amp; sequences in your script tag’s src attribute to plain & characters.

  35. thanks for your quick reply, tried that and i still get the same problems, do you know if there could be another problem?

  36. ah, you need a div for the results to go in. try adding <div name="page-content" />.

  37. i added the div, i think in the right place, not working still, not sure if i added the div correctly though.

  38. sorry, my mistake. the div snippet should be <div id="page-content" />. you also need to close the <script> tag just before it with </script>.

    i made a local copy with those changes, and it seems to work.

  39. Thanks for this app, I have been looking for something like this for a long time.
    My question is how I can keep it from switching to google results page instead of my site page. I don’t see where I made a mistake in the coding. Can you help?

  40. Ryan,

      I am a beginner to write the scripts.
    Here is the code, I modified from your source code.

    <form class=”form” method=”get” action=”http://www.google.com/search”
      onsubmit=”new site_search(‘http://www.myname.com’, q.value); return false;”>
      <input type=”hidden” name=”sitesearch” value=”http://www.myname.com” />
      <input type=”text” name=”q” id=”query” value=”” />
      <input type=”submit” value=”search” />
    </form>

    <script type=”text/javascript”
      src=”http://www.google.com/uds/api?file=uds.js&amp;v=1.0&amp;key=mykey”>
    </script>
    <script type=”text/javascript” src=”ajax_search.js”></script>

    After I enter something to search, it will jump out to google and show the following message:

    Your search – test – did not match any documents.

    Suggestions:
    Make sure all words are spelled correctly.
    Try different keywords.
    Try more general keywords.
    Try fewer keywords.

    Please help me to find the issue.

    Thanks,

    Stephen

  41. Hello Ryan, many many thanks for the script……

    may i know how to implement paging like (pages : 1,2,3,4) if I need not all the results in the same page, I want 10 or 20 records per page…

    thanks,

    Ahmad.

  42. cool, this is a helpful little page.
    Can you tell me, is it possible to exclude certain pages from the results? or limit the search to one directory within the domain?

  43. I am here with Carl; I love the idea of ajax, but I really need the results to open in a new page, designed specially for the “Search Results” . I am a good designer, but terrible coder, and I love buy a brew for a person who could explain how to get the search query to a new page, that would then trigger the ajax form to display results in the div. anyone ?

    I would paypal you money for a sixpack!

    thanks.

  44. Thanks so much for this!
    It was working well for us, for about a month and now seems to be broken.
    Have there been any changes?

  45. @Loki, you’re right, looks like Google changed the response format. I’ve updated the script, it should work now. thanks for the ping!

  46. Please guide how to modify the script if search text box “query” and a button to search lies in master page and for results I am having a separate page say “serachresults.com”.

  47. It’s been a while since I last used this script, works great as always.

    I have a few questions that already have been asked here I think.

    Is it possible to include pages in the results?

    Can I exclude a folder or page within the site?

    Thanks!

  48. @FGaona, by “include pages in the results,” do you mean manually add result links to the ones that google returns? if so, then yes, you can write extra javascript to inject whatever content you want. i don’t have example code, but it shouldn’t be hard if you’re familiar with javascript and the DOM.

    as for excluding results, try adding a keyword with a minus (ie the exclude operator) in front of it.

  49. Hi

    I’ve been using this script for a while but lately I haven’t been getting results, have there been any changes?

    Thanks!

  50. Hi Ryan, Have you used this with JQuery? Right now I am struggling with compatibility, as my Slideshow stopped working after I began installing this search into the CMS. Would be grateful for any help.

  51. sorry to hear about the trouble, alex. i haven’t tried it with jquery, but if you figure out the problem, please do post your solution here!

  52. trying to install this. I will say, my set up may be unique as I am trying to get all this working within the constraints of a cms called Contensis. Overall not bad, but I’m having a heck of a time identifying my Results div. I did not find results_div_id in the js. Do I add it as a var or do I put my results div id in the var results_id that already exists?

    Sorry, its Monday, I feel thick and I need this to work for a prototype demo tomorrow!

  53. good catch, and sorry for the trouble, Alex. you should use the existing results_id var, as you guessed. I’ll update the instructions.

  54. Can u help me to implement pagination for google_ajax_search_api. At present more button is there, But I want to use pagination so I need your help on this please help to implement pagination if possible tell any reference code available. you can send me any data on vijayanekar14@gmail.com waiting for reply…

  55. I have always used this script with very little trouble.

  56. the escape key works in IE but dies in Firefox, any idea why? personally I would have expected the opposite lol otherwise it’s a lovely script

Leave a Reply

Your email address will not be published.