Click here to Skip to main content
15,868,306 members
Articles / Web Development / XHTML

Experimenting with DHTML, Google Search API, and AJAX

Rate me:
Please Sign up or sign in to vote.
4.25/5 (3 votes)
5 May 2009Public Domain3 min read 32.4K   13   15
Learn how to create horizontal tabs of varied search results with DHTML in pure xHTML and JavaScript with AJAX.

Introduction

Google becomes increasingly active every day and is involved in the development of high quality usable source code. They are also exposing their APIs and allowing fellow webmasters to incorporate Google functionality into their own web pages. By the end of this article, you will have created a Google Search with a tabular layout offering various categories of results (see below). If you wish to get highly involved with Google's Services, you should obtain an API key. To find out why this is useful and sign up for one, see the page here. You will need an API key to get results for this project.

Background

The code here is based on a project by Ken Egozi in 2007. You should read his project for an idea of what is going on. I have updated the API code to the new Google recommended standard which has allowed me to explore new features of the API that are demonstrated here. The thing that is great about this project is that it is coded in pure XHTML and JavaScript which means it does not rely on any server side code.

The code

Please enjoy this fully commented script which adds web, image, video, news, site, and local search in a tabular way.

JavaScript
<link href="http://www.google.com/uds/css/gsearch.css" 
  type="text/css" rel="stylesheet" />
<script src="http://www.google.com/uds/api?file=uds.js&amp;v=1.0&amp;key=
        PutYourOwnAPIKeyInHere" type="text/javascript"></script>

<script type="text/javascript">
var searchControl;
window.onload = function() {
    onLoad();
}
function onLoad() {
    // Create a search control
    // Bold text signifies a variable that is changeable.
    searchControl = new google.search.SearchControl();
   
    // Let's get lots of results
    // This can be .SMALL_RESULSET for 4 results per page
    // or .LARGE_RESULTSET FOR 8 results per page.
    searchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);

    // Open in a new window (you can use SELF, PARENT, TOP or BLANK targets)
    searchControl.setLinkTarget(google.search.Search.LINK_TARGET_PARENT);

    // add a regular web search
    var webSearch = new google.search.WebSearch();
    webSearch.setUserDefinedLabel("Web");
    searchControl.addSearcher(webSearch);

    // add an image search
    var imageSearch = new google.search.ImageSearch();
    imageSearch.setUserDefinedLabel("Images")
    searchControl.addSearcher(imageSearch);

    // add a local search
    var LocalSearch = new google.search.LocalSearch();
    LocalSearch.setUserDefinedLabel("Locations")
    searchControl.addSearcher(LocalSearch);

    // change this to a desired location
    // (zip/post code, address, city or even country)
    LocalSearch.setCenterPoint("London, UK");

    // add a video search
    var VidSearch = new google.search.VideoSearch();
    VidSearch.setUserDefinedLabel("Video");
    searchControl.addSearcher(VidSearch);

    // add a news search
    // seems to only get US results.
    var newsSearch = new google.search.NewsSearch();
    newsSearch.setUserDefinedLabel("News");
    searchControl.addSearcher(newsSearch);

    // add a wikipedia search
    var siteSearch = new google.search.WebSearch();

    // here we use Wikipedia as an example
    // of a site to retreive results from. 
    siteSearch.setUserDefinedLabel("Wikipedia");
    siteSearch.setSiteRestriction("wikipedia.org");
    searchControl.addSearcher(siteSearch);

    // setting the draw mode for the Google search
    var drawOptions = new GdrawOptions();

    // use tabbed view
    drawOptions.setDrawMode(GSearchControl.DRAW_MODE_TABBED);

    // set the input field (instead of the default one)
    drawOptions.setInput(document.getElementById('query'));

    // actually write the needed markup to the page
    searchControl.draw(document.getElementById("searchcontrol"), 
                                               drawOptions);
    // set the google logo container
    GSearch.getBranding(document.getElementById("branding"));
}

var query = null;
document.onkeydown = function(event) { kd(event); };

function kd(e) {
    // make it work on FF and IE
    if (!e) e = event;
    // use ESC to clear the search results
    if (e.keyCode == 27)
    searchControl.clearAllResults();
    // get the input field
    if (query == null)
    query = document.getElementById('query');
    // and move the focus in there
    query.focus();
}
</script>

<style type="text/css">
body
{
font-family: verdana;
text-align: center;
}
#queryContainer
{
margin-bottom:2em;
width: 80%;
margin-left:auto;
margin-right:auto;
}
#query
{
border:1px solid silver;
width: 100%;
}
#searchcontrol
{
width:80%;
margin-left:auto;
margin-right:auto;
text-align:left;
}
.gsc-control 
{ 
width: 100%; 
}
</style>
</head>
<body>
<div id="queryContainer">
<input type="text" name="query" id="query" /><br/>
<div id="branding"></div>
</div>
<div id="searchcontrol"></div>

Potential problems

As you may have noticed, wherever a person types on the page, the focus will automatically be on the input field for the search. While this is very user-friendly, it yields one major problem. Some tabs make use of their own option fields (for example, the Local Search) which allows the user to specify their area. The problem here is that if the user attempts to fill the box, the text will appear in the search input field. This can be fixed by removing this code:

JavaScript
if (query == null)
    qquery = document.getElementById('query');
    // and move the focus in there
    query.focus();
}

So that you are left with:

JavaScript
var query = null;
document.onkeydown = function(event) { kd(event); };
function kd(e) {
    if (!e) e = event;
    if (e.keyCode == 27)
        searchControl.clearAllResults();
}

This will remove the ability to automatically focus on the search input field. However, I have not removed it by default as this conflict may not occur depending on what Google functions you choose to use.

And you're done...

It should work like a charm now with all the different functions of the Google Search API that you added. Feel free to make adjustments and modifications to it, but if you do something you think is worth telling us about, by all means do.

Further information

AJAX is becoming increasingly popular, and is the basis of the new Web 2.0. The technologies demonstrated today are constantly evolving, and you have just witnessed the tip of the iceberg. Further information regarding the Google Search API as well as other APIs can be found here on the Google website. You can even want to add a blog search to the tabs, which is easy enough to find out.

Thank you for reading

Thank you for reading about AJAX and the Google Search API. I would also like to thank Ken Egozi for his project which is very resourceful. If you have any queries or ideas, please don't hesitate to leave a message.

License

This article, along with any associated source code and files, is licensed under A Public Domain dedication


Written By
Other
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questioncode bug Pin
chrisdavies2327-Nov-12 9:24
chrisdavies2327-Nov-12 9:24 
GeneralTweaking this code Pin
ercatli28-Feb-10 10:04
ercatli28-Feb-10 10:04 
GeneralRe: Tweaking this code Pin
SamNazarko28-Feb-10 10:33
SamNazarko28-Feb-10 10:33 
Hey,

Glad you like the article. The link targets are for setting how the link will open, not where it will be displayed. You could experiment with a DHTML layer if you're using a panel, but sending content to a new page will require server side scripting, unless you use a form on the side panel to activate a second page and parse the request from the querystring, running "searchcontrol.Execute". This would require a significant rewrite of the above code.

Regarding using a button to initiate search. This doesn't seem like a difficult process. What I would do is remove the automated search when you type text, and add a button with an onclick event that grabs the text from the box and runs "searchcontrol.Execute"

Hope this helps a bit,

Sam.
GeneralRe: Tweaking this code Pin
ercatli28-Feb-10 11:27
ercatli28-Feb-10 11:27 
GeneralRe: Tweaking this code Pin
SamNazarko28-Feb-10 20:41
SamNazarko28-Feb-10 20:41 
GeneralRe: Tweaking this code Pin
ercatli1-Mar-10 1:02
ercatli1-Mar-10 1:02 
GeneralRe: Tweaking this code Pin
SamNazarko1-Mar-10 7:13
SamNazarko1-Mar-10 7:13 
GeneralRe: Tweaking this code Pin
ercatli1-Mar-10 9:59
ercatli1-Mar-10 9:59 
GeneralRe: Tweaking this code Pin
SamNazarko1-Mar-10 11:40
SamNazarko1-Mar-10 11:40 
GeneralRe: Tweaking this code Pin
ercatli1-Mar-10 11:53
ercatli1-Mar-10 11:53 
Questionexcellent post Pin
Dibyendu Biswas1-Dec-09 0:27
Dibyendu Biswas1-Dec-09 0:27 
AnswerRe: excellent post Pin
Dibyendu Biswas1-Dec-09 1:25
Dibyendu Biswas1-Dec-09 1:25 
QuestionGoogle Search in subfolders of website Pin
mshubhu16-Jun-09 1:34
mshubhu16-Jun-09 1:34 
Generalnice Pin
Jeff Circeo6-May-09 12:48
Jeff Circeo6-May-09 12:48 
GeneralRe: nice Pin
SamNazarko8-May-09 9:42
SamNazarko8-May-09 9:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.