Get Related Terms Instantly with Ajax

Get Related Terms Instantly with Ajax

Pull Yahoo! related search suggestions into a web page without clicking a link, a form button, or the Refresh button.

Though widely used, JavaScript has never been considered an indispensable development language. That perception is changing, though, thanks to improvements in web browsers. Now that most widely used web browsers support a standard form of JavaScript, developers can spend their time writing code rather than tweaking the code they've already written. Since a single block of code can work across different browsers, JavaScript is back in the spotlight.

JavaScript's most impressive use is in combination with XML-based services, such as Yahoo! Web Services. Because JavaScript can make requests from the user's machine and doesn't require a page refresh, information can be updated almost instantly without the user clicking a link, clicking a form button, or reloading the page. This makes very interactive, dynamic pages possible. The name for this type of JavaScript is Asynchronous JavaScript + XML, or Ajax for short.

A personal TagCloud on a weblog

This hack is a simple Ajax application that uses Yahoo! Web Services as a data source. As you type in standard HTML text input, JavaScript is in constant communication with the Yahoo! API. With every letter added, the script checks to see if Yahoo! has related search suggestions for the current search term. Related search suggestions are simply phrases that are related to any query, and they're displayed below the text input as you type. This way, if you're typing activeX control into the form, you can see suggested alternate terms like active volcanoes and free activeX along the way.

The Code

This script relies on the XML HTTP object to send and receive responses from a server, and to parse those responses into objects that JavaScript can manipulate. When the page loads, an XML HTTP object is created. The user-input text field has an onkeyup event, so that when the user's input has a keystroke, the getAlts( ) function contacts the Yahoo! Search Web Services, looking for related search terms. If there are no related terms, nothing happens. If related terms are found, the printResponse( ) function formats the related search terms as HTML and prints them to the page with the innerHTML property of a <div> tag below the form.

This code is a standard HTML file, and it doesn't need to reside on a web server. Simply open a text editor, such as Notepad, add the following code, and name the file relatedterms.html:

	<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

			<title>Related Terms</title>
			<script language="javascript" type="text/javascript">
enablePrivilege("UniversalBrowserAccess"); var xmlhttp=false; /*@cc_on @*/ /*@if (@_jscript_version >= 5) // Verify that the browser can load the xmlHttp object. try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { xmlhttp = false; } } @end @*/ if (!xmlhttp && typeof XMLHttpRequest!='undefined') { xmlhttp = new XMLHttpRequest(); } // Accepts a related term, and makes it a Yahoo! link function getLink(r) { var o = "<a href=\"" o = o + escape(r) + "\">" + r + "</a>"; return o; } // Accepts the Yahoo! Search Web Services response, and // prints to the page as HTML function printResponse(xml) { //
enablePrivilege("UniversalXPConnect"); var results = xml.getElementsByTagName("Result"); var numOfResults = results.length; if (numOfResults > 0) { var out = ""; for (var i=0;i<numOfResults;i++) { out = out + "<li>" + getLink(results[i].firstChild.nodeValue) +
"</li>"; } var s = document.getElementById('suggest'); s.innerHTML = "You might also try:<ul>" + out + "</ul>"; } } // Accepts a full or partial search term, and looks for // related terms with a Yahoo! Search Web Services request function getAlts(t) { var yurl = "" yurl = yurl + "relatedSuggestion?appid=YahooDemo&query=" +
escape(t); //
enablePrivilege("UniversalXPConnect"); try {"GET", yurl, true); } catch (E) { alert(E); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState==4) { printResponse(xmlhttp.responseXML); } } xmlhttp.send(null) } </script> </head> <body> <h2>Yahoo! Related Terms</h2> <form> <input name="txt" type="text" value="" onkeyup="getAlts(this.value)" /> </form> <div name="suggest" id="suggest"></div> </body> </html>

As you can see, the HTML for this page is straightforward, and the work is done in the JavaScript section in the <head> of the page. Be sure to request a unique application ID for the script and use it in the code.

Running the Hack

To avoid potential problems with cross-site scripting exploits, by default browsers do not allow JavaScript to call pages from other domains. And because Yahoo! Search Web Services are at another domain, this script will require some browser tweaks to run. If you were to implement this script on a web site, you'd need to set this up in a different way. But this example is intended to show what's possible with Ajax, rather than the perfect way to deploy an Ajax application to other users.

When you open this page in Internet Explorer, you'll probably see a yellow security warning like the one shown below the Address bar in Figure.

Internet Explorer security warning

Click the yellow banner, and choose Allow Blocked Content…to let the script contact Yahoo!.

For Firefox, you'll need to uncomment the following text by removing the double slashes at the beginning of its line in relatedterms.html:"UniversalXPConnect");

This will allow the browser to contact a remote domain, and the first time it tries to run, you'll see a request to allow the privilege change, as shown in Figure.

Firefox security request

Check the "Remember this decision" box and then click the Allow button. If you ever spot this dialog while browsing a file that you didn't write, you'll want to click Deny instead. But because you're in control of the information being passed around, you can be sure you're not doing anything malicious.

With the security settings behind you, you can start playing with the script. As you type, the JavaScript contacts Yahoo! for suggestions. Try searching for the tech term activeX Component, and you'll see different suggestions appear along the way. After you type the first six letters (active), several suggestions appear below the form, as shown in Figure.

Yahoo! related terms for "active"

Keep typing, and new suggestions appear as you type the X, as shown in Figure.

Click any of the suggestions to view the search results for that phrase at Yahoo!. The complete phrase activeX Control will yield even more suggestions.

 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows