Friday, November 25, 2011

Get Google suggestions in Sencha Touch application

Recently I was working on a project where requirement was to bring Google suggestions to sencha touch app. Exact requirement was to build auto suggest search box with suggestions from Google search.

I tried to get it using Ajax Request but it was not working because it become cross domain request so I was getting error that "Access Denied".  After that I tried to get it using JsonStore using scriptTagProxy Check the code below.


var searchStore = new Ext.data.JsonStore({
                        fields: [],
                        root: 'items',
                        proxy:new Ext.data.ScriptTagProxy({
                           url: 'http://suggestqueries.google.com/complete/search?hl=en&ds=yt&client=youtube&hjson=t&cp=1&q='+search+'&key=&format=5&alt=json'
                         })
                    });

Here biggest issue is Google suggest returns JSON but not in key value pair. It just gives text of suggestions as follow. For example if we search for query we get following output.

["QUERY",["query","query in access 2007","query xl 2011","query gratis xl","query kartu tri 3","query optimization","query opmin 4 2 axis","query bolt browser simpati 2011","query telkomsel bolt handler","query in access 2010"],["","","","","","","","","",""]]

Now above data will not be loaded in store as we don't have any fields here. So how to access data. You have two options.

Override Ext.data.Connection method which is used in Ext.Ajax and add support for cross domain access.


Now above option seems bit difficult and time consuming.  I have another solution for it. Add load listeners to store.


searchStore.on({                     
                       load:function(store,records){                     
                          console.log(store.proxy.reader.jsonData);
                       }
                    });              
searchStore.load();


store.proxy.reader.jsonData, this will give you jsonData returned in response. You can use it to display suggestions the way you want.

Hope this helps you.

Important Note : I am not sure whether it's legal to use Google result in any application or not. But here the project mentioned was of the company, which is certified google application company. So please check the Google policy before using Google suggestions in your application.

No comments:

Post a Comment