How to Add Auto Complete to Your Google Custom Search Engine

This tutorial will show you how to use the "Popular Queries" feed from your Google Custom Search Engine (CSE) as a data source for a jQuery autocomplete.



Preface

Google CSE Homepage
Google’s Custom Search Engine (CSE) allows you to create a robust search feature for your Web site. They offer a free,
ad-supported version and a premium business version that starts at $100 per year. Additionally, CSE provides a wide range of metrics, ranging from integration with
Google Analytics to a feed of popular search queries.
This tutorial will show you how to use PHP and jQuery to add an auto complete feature to CSE’s default search box using the popular search queries feed as the data source.
In order to successfully use this technique on your site, you’ll need your own Google CSE and a decent amount of search traffic (to ensure we have a nice set of data for
our auto complete list).
Don’t worry if you don’t meet all of these requirements—you can still follow along. Google often citesMacWorld’s CSE implementation
as an example, so I’ll be using their search feed in this tutorial. Feel free to do the same if you’d like.
Let’s get started.

Step 1: Create Your Search Page

The first thing we’ll do is add the CSE’s default search code to a new XHTML page. You can find this by logging into your control panel and clicking “code.” It will
look something like this.
  1. <form action="http://www.google.com/cse" id="cse-search-box">  
  2.   <div>  
  3.     <input type="hidden" name="cx" value="003198751674731024891:ovffo1orlum" />  
  4.     <input type="hidden" name="ie" value="UTF-8" />  
  5.     <input type="text" name="q" size="31" />  
  6.     <input type="submit" name="sa" value="Search" />  
  7.   </div>  
  8. </form>  
  9. <script type="text/javascript" src="http://www.google.com/coop/cse/brand?form=cse-search-box&lang=en"></script>  
Save this document in a new folder as search.html and open it in your browser. Search for something to make sure the search box works.
Google CSE Search Results

Step 2: Adding the jQuery Auto Complete Function

Although the jQuery UI has an auto complete function built in, you might find the 
auto complete plugin
 created by Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, and Jörn Zaefferer is a little easier to use. Download
jquery.autocomplete.zip and unzip it.
The plugin’s archive contains a variety of different scripts for many implementations. While the best practice would be to move the scripts and stylesheets we’re
going to use to appropriately named folders inside of our page’s root, in the interest of simplicity, let’s just drag the
“jquery-autocomplete” folder into the folder our search.html is in.
The plugin comes with a demo illustrating how the auto complete could be used with city names. Let’s make sure jQuery and our plugin are working properly
by hooking our Google search box up to the list of cities. In search.html, add the following inside the tag.
  1. <script type="text/javascript" src="jquery-autocomplete/lib/jquery.js"></script>  
  2. <script type="text/javascript" src="jquery-autocomplete/jquery.autocomplete.js"></script>  
  3. <script type="text/javascript" src="jquery-autocomplete/demo/localdata.js"></script>  
  4. <link rel="stylesheet" type="text/css" href="jquery-autocomplete/jquery.autocomplete.css" /><p></p>  
  5.   
  6. <script type="text/javascript">  
  7. $().ready(function() {  
  8.     $("#cse_search").autocomplete(cities);  
  9. });  
  10. </script>  
We’ll also need to slightly modify CSE’s default search code by adding an id attribute to the search box. We’ll call it “cse_search.”
  1. <input type="text" id="cse_search" name="q" size="31" />    
Save search.html and open it in your browser. In the search box, start typing the name of a city; you should see the autocomplete menu.
Starting to enter the name of a city will offer suggestions.

Step 3: Getting the Data Set

In the previous step, we included the “jquery-autocomplete/demo/localdata.js” script. If you open the file and look at it, you’ll see a few different
JavaScript arrays. These are the arrays used to populate auto complete lists in the plugin’s demo files. When we initialized jQuery and instructed the plugin
to auto complete our “cse_search” box, we also told it to get its data from the cities array:
  1. $().ready(function() {  
  2.     $("#cse_search").autocomplete(cities);  
  3. });  
Now we need to instruct jQuery to use our popular queries feed as its data source. But how?
We’ll use a little PHP to pull in the popular queries feed, parse it, and echo out a valid JavaScript array. By including the PHP file as we would
a regular JavaScript file, it will be executed behind the scenes and the Web browser will think it’s reading a static JS file.
Additionally, we’re also going to supplement our popular queries feed with terms that we specify. The terms we specify here may not be searched often
enough to show up as a “popular query,” but they still may be useful to have in our auto complete list. For instance, terms for which you’ve created
Google subscribed links or terms that monetize well with
AdSense for Search.
Create a file inside the “jquery-autocomplete” folder called searchdata.php and paste in the following:
  1.     /* This script parses the Popular Queries feed from Google's CSE product and outputs 
  2.        the recent queries in a JavaScript array for use with the jQuery Autocomplete plugin. */  
  3.   
  4.     // There may be some search queries you want to include in the autocomplete box  
  5.     // that aren't necessarily popular searches and therefore don't show up in your   
  6.     // Google CSE feed.  You can add those terms to this array to ensure they show up.  
  7.     // You will want to make sure you enter the terms in lowercase.   
  8.     $data = array(  
  9.         "steve jobs",  
  10.         "macbook pro",  
  11.         "macbook air",  
  12.         "itunes",  
  13.         "ipod"  
  14.     );  
  15.   
  16.     // Load the Popular Queries RSS Feed from Google's CSE using SimpleXML  
  17.     // The URL is available by clicking "Statistics" from inside your CSE control panel.  
  18.     if (!$s = simplexml_load_file("http://www.google.com/coop/api/003198751674731024891/cse/ovffo1orlum/queries?sig=__GaZojo71AtdDbVHqJ9KDPhwXAhk=")) {  
  19.         exit();                                         // cheap error handling.  
  20.     }  
  21.   
  22.     // Create an array of all the popular queries.   
  23.     foreach($s->item as $item) {  
  24.         $search_term = strtolower(trim($item->title));   // trim() is used to remove whitespaces.  
  25.         if (!in_array($search_term$data)) {           // ensure there are no duplicates.   
  26.             $data[] = $search_term;                     // add $search_term to data array.  
  27.         }  
  28.     }     
  29.     sort($data); //alphabetize the array  
  30.   
  31.     // Format the data for JavaScript output.  
  32.     foreach($data as $search_term) {  
  33.         $js_data[] = "\"" . $search_term . "\"";      
  34.     }     
  35.       
  36.     // Let's inform the browser that we're sending JavaScript.  
  37.     header("Content-type: text/javascript\n\n");  
  38.       
  39.     // Next we'll escape from PHP and create a JavaScript array. Inside the array, we'll return to  
  40.     // PHP and use implode() to return a comma-separated string of all the data inside $js_data.  
  41. ?>  
  42. var searchdata = [echo implode($js_data", "); ?>];  
Output of searchdata.php
If you’re using your own CSE feed, you’ll want to replace the URL on line 7. In this example, I used the overall popular queries feed for MacWorld.com.
You can use your own overall popular queries feed by going to your CSE Manage Page > Statistics >
Overall. Other available options are popular query feeds by day, week, and month.
Next, we’ll need to remove the demo’s localdata.js script from search.html and replace it with our searchdata.php file:
  1. Replace:  
  2. <script type="text/javascript" src="jquery-autocomplete/demo/localdata.js"></script>  
  3.   
  4. With:  
  5. <script type="text/javascript" src="jquery-autocomplete/searchdata.php"></script>  
We’ll also need to slightly modify our initialization code:
  1. Replace:  
  2. $("#cse_search").autocomplete(cities);  
  3.   
  4. With:  
  5. $("#cse_search").autocomplete(searchdata);  
Now let’s upload everything to the server and give search.html a shot. If everything is working like it’s supposed to, your auto complete
should be working perfectly.
A working examples of the CSE RSS-powered autocomplete.

A Word on Caching

Sites that receive a significant amount of traffic may want to consider caching the search array. Having the server parse the feed
each time someone types into the search box will use a significant amount of resources. You can cache the results by replacing your
searchdata.php file with the following:
Note: The script will create the cache for the first time, but it must have write access to the directory you’re
going to store it in.
  1.     /* This script parses the Popular Queries feed from Google's CSE product and outputs 
  2.        the recent queries in a JavaScript array for use with the jQuery Autocomplete plugin. */  
  3.   
  4.     // Set information about the cache  
  5.     $cache_path = "cache/searchdata-cache.txt";   // the directory must be writeable by the server  
  6.     $cache_time = 3600;                           // seconds to keep the cache for  
  7.   
  8.     // Determine if the cache is there  
  9.     $cache_exists = @file_exists($cache_path);    // returns true or false  
  10.   
  11.     // Let's inform the browser that we're sending JavaScript.  
  12.     header("Content-type: text/javascript\n\n");  
  13.   
  14.     // If there is a cache and it's old, delete it. If it's current, use it.  
  15.     if ($cache_exists) {  
  16.         $cache_age = filectime($cache_path);  
  17.         if ($cache_age < (time() - $cache_time)) {  
  18.             unlink($cache_path);                  // delete the cache  
  19.         } else {  
  20.             include($cache_path);                 // load the cache  
  21.             exit();                               // no need to continue processing  
  22.         }  
  23.     }  
  24.   
  25.     // There may be some search queries you want to include in the autocomplete box  
  26.     // that aren't necessarily popular searches and therefore don't show up in your   
  27.     // Google CSE feed.  You can add those terms to this array to ensure they show up.  
  28.     // You will want to make sure you enter the terms in lowercase.   
  29.   
  30.     $data = array(  
  31.         "steve jobs",  
  32.         "macbook pro",  
  33.         "macbook air",  
  34.         "itunes",  
  35.         "ipod"  
  36.     );  
  37.   
  38.     // Load the Popular Queries RSS Feed from Google's CSE using SimpleXML  
  39.     // The URL is available by clicking "Statistics" from inside your CSE control panel.  
  40.     if (!$s = simplexml_load_file("http://www.google.com/coop/api/003198751674731024891/cse/ovffo1orlum/queries?sig=__GaZojo71AtdDbVHqJ9KDPhwXAhk=")) {  
  41.         exit();                                         // cheap error handling.  
  42.     }  
  43.   
  44.     // Create an array of all the popular queries.   
  45.     foreach($s->item as $item) {  
  46.         $search_term = strtolower(trim($item->title));   // trim() is used to remove whitespaces.  
  47.         if (!in_array($search_term$data)) {           // ensure there are no duplicates.   
  48.             $data[] = $search_term;                     // add $search_term to data array.  
  49.         }  
  50.     }     
  51.     sort($data); //alphabetize the array  
  52.   
  53.     // Format the data for JavaScript output.  
  54.     foreach($data as $search_term) {  
  55.         $js_data[] = "\"" . $search_term . "\"";      
  56.     }     
  57.   
  58.     // Setup the cache  
  59.     $fp = fopen($cache_path"w");  
  60.   
  61.     // Create the JavaScript array  
  62.     $js_array = "var searchdata = [" . implode($js_data", ") . "];";  
  63.   
  64.     // Write the array to the cache  
  65.     fwrite($fp$js_array);  
  66.   
  67.     // Close the cache  
  68.     fclose($fp);  
  69.   
  70.     // Include the cache file.  
  71.     include($cache_path);  
  72. ?> 

COMMENTS

Name

©2012 Oceninfo.co.cc,2,10:29 IST,1,2012,1,Adfly Bot,2,AFCEH,1,Ajax security,1,all posts for education purpose only...www.facebook.com/princebhalani,1,Android,1,android developer,1,android phone,1,android phone-1,1,anonymous email,1,Anti-Trojan software,8,Antivirus,1,Apple,1,article marketing,1,at risk,1,attacks,1,australian federal police,1,Auto Clicker,1,Auto surfer,1,backtrack link,2,Bank Hacking,2,BCMSN,2,BIOS Update,1,Blockchain,1,Blog and tagged Ransomware,1,boot fast...,1,boot xp faster,1,Business Deals,1,Bypass Antivirus and Hack Window Systems,1,CCIE,2,CCNA,2,CCNP,2,CEH,2,challenge-response system,1,Changing Root Bridge Election Results,2,code,2,commands,1,company deals,1,Computer Hacking,3,Connect,1,cookie stealing,3,Country,1,Crack,1,Credit Card Fraud,2,credit cards,1,Cryptography,1,cyber cell updated,1,cyber security,1,DATA CARD TRICK,1,delhi,1,Digital Marketing,1,direct admission in any colleges,2,Direct Link,3,Directory Traversal Attacks,1,Dos and Ddos,1,DotNetNuke Remote File Upload Vulnerability,1,Earn Lots of money,3,EARN MONEY PART2,1,earnings in$,1,email hacking,4,email spoofing,2,Er Prince Bhalani jobs,1,Ethical Hacker job,1,ethical hacking,8,exploit,1,facebook autoliker,1,Facebook tricks,3,Fake Mail,1,fake sms,1,FB hackz,1,FBI,1,FBI HACKERS,2,FBI Jobs,2,featured,6,Finger scan,1,fingerprint Hacking,1,format without pain,1,Free Download,1,Free Flash Templates,1,free hacking book,5,Free Recharge,1,free sms,2,Freebeacon,1,friendship day,2,friendship day image,2,friendship image,1,Future Computer,2,future of hacking,1,Gadgets,1,good clean fun,1,google,3,Google Ads,1,google adsense account,1,Google hacking,3,google hacks,1,google search,1,hack,2,hack the world,2,HACK WEBSITES USING SQL INJECTION,2,hacker,1,hacker uni,1,hacker/LPT/etc,1,hackers,2,Hackerz info,1,hacking,4,hacking games,1,hacking matterial,1,HACKING OFER,1,hacking softwares,1,hacking tools,2,Hacking with Mobile phones,1,HackingTeacher Security Solutions,1,hacks,1,hijack,1,history of hacking,1,How to,8,How to Hack,37,how to play,1,How to sniff,1,html,1,HTTPS/SSL secured sites,1,I LOVE YOU VIRUS,1,i-phone hacking,1,ICITAM 2012,1,iCloud Era,1,In Flow,1,indian cyber cell,4,information security,1,interesting,1,inurl:fcklinkgallery.as,1,IP hacks,1,iphone,1,IT Act,1,IT Decision Maker,1,IT Implem_App/LOB Spec,1,IT Implem_Desktop/EndUser Spec,1,IT Implem_Infrastructure Spec,1,IT Implem_IT Generalist and IT Manager.,1,it security,1,java,1,jobs for ethical hacker,3,jobs in hacking,5,Joe job,1,Just for education purpose only,1,Kaspersky,1,kaspersky crack 2013,1,keyboard hacking,1,keyloggers,1,keywords,1,Laptop Tracking,1,Laws of computer crime,1,Learn Cracking,1,Learn Website Hacking,7,Linkbucks Bot,1,Macromedia Flash,1,make some rules...|||_|||,1,malicious code,1,Malware,1,malware analysis,1,man in the middle attack (LAN),1,master,1,master list,1,metasploit,3,Microsoft scams,1,mobile,1,mobile recharge,1,moblie phone hacking,1,munging,1,network hack,1,Network Sniffers,1,new command set,1,new projects,1,nmap,1,No Survey,1,not infrequent,1,online scanners,1,paisa live hack,1,panetration for educational purpose only,1,Parental Controls,1,password hacking,4,Password sniffing with arp poisoning,1,PC TIPS,1,PE_PARITE (Trend Micro),1,penetration testing,1,pharming,1,phishing,1,phone hacking charged,1,PHP,1,pin ball,1,Play WMV Files,1,Press Trust of India / New Delhi Aug 15,1,Prime minister,1,prince bhalani,1,princebhalani,1,Professional job in FBI,1,Professional Penetration Testing,1,Programming,1,Programming of virus,2,protect my pc against hackin,1,proxy list by http,1,Proxy SOCKS Port,1,R-Admin With Key,1,Radmin,1,RAW Jobs,1,Real Hackers vs fake ethical hackers. ..:),1,Register of Known Spam Operations (ROKSO),1,repair corrupt hard disk,1,RFT,1,Robbery,1,Rupert Murdoch,1,SAMPLE,1,Sample dynamic flash template from TM website,1,Scams,2,Scanned Vulnerabilities,1,SEA,2,search engine hacking,1,Search Operators,1,Security,2,Security breach,1,security code brack,1,SEM,4,SEO,112,SEO Mistakes,1,SEO TOOLS,1,SEO Tricks,3,SERM,1,SERP,1,Session Hijacking,4,SET,1,shell commands...,1,shell list with download,1,SITES,1,Smart Home,1,Smartphones,1,SMM,1,SMO,2,sms spoofing,1,SMTP Servers,1,Sniffing passwords,1,Sothink SWF Decompiler,1,spam cocktail (or anti-spam cocktail),1,spam trap,1,spear phishing,2,SQL hacking,2,SQL Injection Attacks by Example,2,SSL,1,SSL Analysis,1,starting of help,1,System Information,1,System Restore,1,Tablet in 1000,1,Tablets,1,Temporary Email Service,1,time need,1,timer,1,tracing,1,Traffic,3,tricks,5,Tricks and Tips,1,Trojan,1,Trojan tools,1,Trojans and Backdoors,2,trojon,7,Turbo C++,1,UK phone hacking,1,UK phone hacking arrest,1,USA JOBS,4,Virus,2,virus writing,2,VPN,1,vulnerabilities,1,vulnerability assessment,1,W32/Pate (McAfee),1,W32/Pinfi (Symantec),1,Washington,2,web hacking,6,web security,1,Website Development,1,Website Hacking,3,White House,1,wifi hacking,3,Win32 : parite (Avast),1,Win32.Parite (Kaspersky),1,Win32/Parite,1,windows,2,Windows 8 event for IT Professionals,1,wirless hack,1,WordPress,1,WordPress hacking,1,working with Virus and worm,9,XP Hacking,1,xp hacking-1,1,XP part 3,1,xss hacking,1,
ltr
item
Group Of Oceninfo: How to Add Auto Complete to Your Google Custom Search Engine
How to Add Auto Complete to Your Google Custom Search Engine
How to Add Auto Complete to Your Google Custom Search Engine
http://net.tutsplus.com/wp-content/themes/nettuts/site_images/button_src_nm.jpg
Group Of Oceninfo
https://oceninfo.blogspot.com/2013/08/how-to-add-auto-complete-to-your-google.html
https://oceninfo.blogspot.com/
https://oceninfo.blogspot.com/
https://oceninfo.blogspot.com/2013/08/how-to-add-auto-complete-to-your-google.html
true
6415817773321450103
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS CONTENT IS PREMIUM Please share to unlock Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy