Toast
Toast

Reputation: 657

Use Google Suggest with JavaScript

I want to add the autocomplete / suggest feature of the Google Search to an input in a HTML page.

If I open a URL like this with Firefox:

suggestqueries.google.com/complete/search?client=firefox&q=stacko&callback=abc

It downloads a file like this:

["stacko",["stackoverflow","stackoverflowerror","stackoverflowexception","stackops","stackoverflow api","stackoverflow careers","stackoverflow java","stackoverflow deutsch","stackoverflow wiki","stackoverflow reputation"]]

How can I do this in JavaScript? I want to get an array with the results.

// Edit: Here is my tried code:

var txtFile = new XMLHttpRequest();
txtFile.open("GET", "http://suggestqueries.google.com/complete/search?client=firefox&q=stacko&callback=abc", true);
txtFile.onreadystatechange = function() {
    text = txtFile.responseText;
    alert(text);
}
txtFile.send(null);

This creates an empty alert.

Upvotes: 2

Views: 4875

Answers (3)

Xotic750
Xotic750

Reputation: 23472

You could use something like this, it incorporates the Google search URL, combined with YQL and jQuery UI autocomplete

HTML

<div class="ui-widget">
    <input id="search" />
</div>

Javascript

$(function () {
    $("#search").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22http%3A%2F%2Fsuggestqueries.google.com%2Fcomplete%2Fsearch%3Fclient%3Dfirefox%26q%3D" + encodeURIComponent(request.term) + "%22&format=json",
                dataType: "jsonp",
                success: function (data) {
                    response(data.query.results.json.json[1].json);
                }
            });
        },
        minLength: 2
    });
});

On jsfiddle

I don't have the time to write all the jquery stuff here in vanilla javascript, so you can use it as a proof of concept. But to be honest this is one of those times that I would actually use jquery and jquery UI rather than reinvent the wheel. There are of course other 3rd party libraries out there that could do a similar thing for you. And, as above you could use different sources for the autocomplete by changing the YQL search URL.

Upvotes: 4

dandavis
dandavis

Reputation: 16726

function addScript(u){ 
   var s=document.createElement('script'); 
  s.src=u;  
  document.getElementsByTagName('*')[1].appendChild(s);
 }


function getQueryWiki(term, callback){    
   var id="i"+Math.random().toString(36).slice(2);
   getQueryWiki[id]=function(data){ callback(data); delete getQueryWiki[id];};
   addScript( "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22http%3A%2F%2Fen.wikipedia.org%2Fw%2Fapi.php%3Faction%3Dopensearch%26search%3D"+
   encodeURIComponent(term)+
  "%26namespace%3D0%22%20&format=json&callback=getQueryWiki."+id );
}


function getQueryGoogle(term, callback){
   var id="i"+Math.random().toString(36).slice(2);
   getQueryGoogle[id]=function(data){ callback(data); delete getQueryGoogle[id];};
   addScript( "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22http%3A%2F%2Fsuggestqueries.google.com%2Fcomplete%2Fsearch%3Fclient%3Dfirefox%26q%3D"+
   encodeURIComponent(term)+
  "%22%20&format=json&callback=getQueryGoogle."+id );
}

//example usage (google):

getQueryGoogle("obam", function(d){
  alert(
     JSON.stringify(
          d.query.results.json.json[1].json,
          null,
          "\t"
     )
  );
});

// displays:

[
    "obama",
    "obamacare",
    "obama immigration",
    "obama phone",
    "obama gun control",
    "obama immigration reform",
    "obama impeachment",
    "obama approval rating",
    "obama net worth",
    "obama speech"
]

//example 2 (wikipedia)

getQueryWiki("obam", function(d){
  alert(
     JSON.stringify(
          d.query.results.json.json[1].json,
          null,
          "\t"
     )
  );
});

//shows:

[
    "Obama",
    "Obama administration",
    "Obamacare",
    "Obama-Biden Transition Project",
    "Obama, Fukui",
    "Obama stimulus plan",
    "Obama Line",
    "Obama for America",
    "Obama Domain",
    "Obama Republican"
]

Upvotes: 6

Ryan
Ryan

Reputation: 5682

Not sure exactly what your going for but like @Ejay said in his comments you could do this:

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function(){
    if(xhr.readyState == 4){
        if(xhr.status == 200){
           //parse the response object
           parse_the_text(xhr.responseText);    
        }
    }else{
      return;
    }
}

var url = "http://suggestqueries.google.com/complete/search?client=firefox&q=stacko";

xhr.open('Get', url, true);
xhr.send(null);

function parse_the_text(google_array){
    for(var i = 0; i < google_array[1].length; i++){  //this is dirty as it relies on response object never changing
        alert(google_array[1][i]);
    } 
}

But I did some testing on jsfiddle and it confirms what dandavis said you can't ajax request to that page.

Upvotes: 1

Related Questions