Customizing Google custom search jsapi (query strings)

3.1k Views Asked by At

Helo,

Im creating Google cse function to search. With this code script does not set query string. it endless refreshing page. Maybe someone know hos ot make it correctly? I just need for every search different page like example: http://page.com/search?q=first+search can i do it somehow with parseParamsFromUrl function?

    <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', style : google.loader.themes.MINIMALIST});
google.setOnLoadCallback(function(){
var cse = new google.search.CustomSearchControl('13707349811359660237:cl5vrpn6mu8');
cse.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
cse.draw('cse');
cse.setNoResultsString('No results for this query, try a different search.');
cse.setSearchStartingCallback({}, function() {
var q = cse.getInputQuery();
window.location.search = '?q='+q;
});
Function parseParamsFromUrl() {
  var params = {};
  var parts = window.location.search.substr(1).split('\x26');
  for (var i = 0; i < parts.length; i++) {
    var keyValuePair = parts[i].split('=');
    var key = decodeURIComponent(keyValuePair[0]);
    params[key] = keyValuePair[1] ?
        decodeURIComponent(keyValuePair[1].replace(/\+/g, ' ')) :
        keyValuePair[1];
  }
  return params;
}
var urlParams = parseParamsFromUrl();
var queryParamName = "q";
if (urlParams[queryParamName]) {
  cse.execute(urlParams[queryParamName]);
}
}, true);
</script>

Any help will be appriciate

2

There are 2 best solutions below

1
On

I answered my question myself. Here is working script

google.load('search', '1', {language : 'lt style: google.loader.themes.MINIMALIST '});
google.setOnLoadCallback(function() {
    var customSearchControl = new google.search.CustomSearchControl('014092587915392242087:l98hzi05fja'); // change this to your unique ID
    customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
    customSearchControl.setLinkTarget(google.search.Search.LINK_TARGET_NEW); // open results in new window
    var options = new google.search.DrawOptions();
    options.setAutoComplete(true);
    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']
    customSearchControl.setSearchStartingCallback({}, function() {
        var q =  customSearchControl.getInputQuery();
        window.location.search = '?q='+q;
    });
}, true);

Now every search appears in url

0
On

You can actually achieve this in JavaScript as you attempted in your question and further improve it greatly by using the HTML5 history API rather than refreshing the page. This is how I did it:

First of all we need the jQuery plugin for getting the params (not necessary if you have PHP but just for reference):

(function($) {
    $.QueryString = (function(a) {
        if (a == "") return {};
        var b = {};
        for (var i = 0; i < a.length; ++i)
        {
            var p=a[i].split('=');
            if (p.length != 2) continue;
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        }
        return b;
    })(window.location.search.substr(1).split('&'))
})(jQuery);

Next a function for changing the address without a refresh, providing a fallback for older browsers that don't support the history API:

function pushState(path) {
    if (typeof(window.history.pushState) == 'function') {
        window.history.pushState(null, path, path);
    } else {
        window.location.hash = '#!' + path;
    }
}

And finally the code for Google CSE, assuming your search page is located at /search

google.load('search', '1', {language : 'en', style : google.loader.themes.MINIMALIST});
google.setOnLoadCallback(function() {
    var searchControl = new google.search.CustomSearchControl('YOUR_SEARCH_ID');
    searchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET );
    searchControl.draw('cse');
    searchControl.execute($.QueryString["q"]);
    searchControl.setSearchStartingCallback({}, function() {
            var q =  searchControl.getInputQuery();
            pushState("/search?q=" + q);
    })
}, true);