Automatically Submit Google CSE

This tutorial outlines two techniques to customise¬†Google’s Custom Search Engine:

  1. Generating your own custom styled search form
  2. Fetching the search results on page load rather than the default which requires the Google provided search form to be submitted

This enables you to place your custom styled search form anywhere on your site (for example in a global site header), and when the form is submitted the search results are automatically loaded as soon as the user lands on the search page – as opposed to the default behavior which requires submission of the Google provided search box.

This is a sample global form that I use in my header file, which submits to the url “/search”. I will leave the CSS side to your imagination.

<form id="search" method="get" action="/search">
<fieldset>
<input type="text" name="q" value="" placeholder="Search Records" />
<button type="submit">Search</button>
</fieldset>
</form>

On my search page, the following code displays the Google CSE search box and pre-loads the results which are passed in from PHP’s $_GET. Don’t forget to replace myUniqueID with your Google CSE unique ID.

<!-- div container to display search results -->
<div id="cse" style="width: 100%;">Loading...</div>

<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
  google.load('search', '1', {language : 'en'});
  google.setOnLoadCallback(function() {
    var customSearchControl = new google.search.CustomSearchControl('**myUniqueID**'); // change this to your unique ID
    customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
    customSearchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF); // open results in current window
    customSearchControl.draw('cse'); // set the results div id
    customSearchControl.execute("<?php if (isset($_GET['q'])) echo filter_var($_GET['q'], FILTER_SANITIZE_STRING); ?>"); // run the search using the value of $_GET['q']
}, true);
</script>

2 Replies to “Automatically Submit Google CSE”

  1. This is what i have been looking for for a long time. Is there any way to control the number of search results displayed?

Leave a Reply

Your email address will not be published. Required fields are marked *