Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variable to Google Custom Search Engine

Is it possible to pass a search variable into the Google Custom Search Engine that I have embedded on my website? I can get the search engine to work, but I can't pass it a term via POST (it's coming from a search button on other pages of the website)

I tried to hack the code I found here: http://code.google.com/apis/ajax/playground/?exp=search#hello_world

And this is what I have so far... ($q is the term I am passing to it)

<script type="text/javascript">
    google.load('search', '1', {language : 'en'});

    function OnLoad()
    {
        var customSearchControl = new google.search.CustomSearchControl('***my key****');
        customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
        customSearchControl.draw('cse');
        searchControl.execute("$q");
    }
    google.setOnLoadCallback(OnLoad);
</script>   

Thanks

like image 611
Matt Avatar asked Feb 19 '10 16:02

Matt


People also ask

Is there an API for Google search?

Google Web Search API has been deprecated and replaced with Custom Search API (see http://code.google.com/apis/websearch/).

How do I use Google Custom Search API?

Custom Search JSON API requires the use of an API key. An API key is a way to identify your client to Google. After you have an API key, your application can append the query parameter key=yourAPIKey to all request URLs. The API key is safe for embedding in URLs, it doesn't need any encoding.


1 Answers

Sorry, I know it's a crappy answer, but you've actually got it right apart from referencing the wrong variable name. Oh, also, as an aside, I would also hope you're doing some kind of sanitisation on $q, in case someone posted something like this to your form: term"); alert("aha!

    customSearchControl.draw('cse');
    searchControl.execute("$q");

should be:

    customSearchControl.draw('cse');
    customSearchControl.execute("$q");

Also, thank you for the question - I was looking for how to do this myself!

like image 179
Shabbyrobe Avatar answered Sep 21 '22 22:09

Shabbyrobe