Search code examples
javascriptjsfiddlegoogle-suggest

Google suggestion search for more than one word


i'm working with google-suggestion and i'm trying to get all suggestion. I found and example here

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

javascript code

$(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
    });
});

http://jsfiddle.net/Xotic750/qjy6H/

when i enter more then one word it do not work(don't show suggestions).
Thanks for help. there is another question on this theme. Can i save result to an array and transfer it to html page? and how can i do that?


Solution

  • You need to replace spaces in request.term by a + sign:

    Here is the working JS code:

    $(function () {
        $("#search").autocomplete({
            source: function (request, response) {
                var searchTerm = "auto+" + request.term.replace(" ", "+");
                $.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(searchTerm) + "%22&format=json",
                    dataType: "jsonp",
                    success: function (data) {
                        response(data.query.results.json.json[1].json);
                    }
                });
            },
            minLength: 2
        }); });
    

    You can see it working on this codepen: http://codepen.io/adrenalinedj/pen/MyOZGj