Google Custom Search API Autocomplete?

Kram picture Kram · Nov 22, 2011 · Viewed 8.8k times · Source

We're using the google custom search API (paid-for server-side API) to power our search results.

I'd like to add an autocomplete feature to the search - however, does anyone know if there is support for this (either via the server-side API, or via some sort of client-side JSONP?)

I have tried using the autocomplete for the Google Customised search, but this appears to want to draw the search box and display google ads with the results, which I don't want.

Answer

Kram picture Kram · Nov 29, 2011

Got this working something like this - hope this helps someone else :)

$(function () {
  $('input.search')
    .focus(function () { this.select(); })
    .mouseup(function (e) { e.preventDefault(); })
    .autocomplete({
      position: {
        my: "left top",
        at: "left bottom",
        offset: "0, 5",
        collision: "none"
      },
      source: function (request, response) {
        $.ajax({
          url: "http://clients1.google.com/complete/search?q=" + request.term + "&hl=en&client=partner&source=gcsc&partnerid={GOOGLESEARCHID}&ds=cse&nocache=" + Math.random().toString(),
          dataType: "jsonp",
          success: function (data) {
            response($.map(data[1], function (item) {
              return {
                label: item[0],
                value: item[0]
              };
            }));
          }
        });
      },
      autoFill: true,
      minChars: 0,
      select: function (event, ui) {
        $(this).closest('input').val(ui.item.value);
        $(this).closest('form').trigger('submit');
      }
    });
});