Welcome!

Virtualization Authors: Jeremy Geelan, Maureen O'Gara, Reuven Cohen, John Savageau, Greg Ness

Related Topics: AJAX & REA

AJAX & REA: Article

Real-World AJAX Book Preview: Using TinyAjax to Create Live Search

Real-World AJAX Book Preview: Using TinyAjax to Create Live Search

This content is reprinted from Real-World AJAX: Secrets of the Masters published by SYS-CON Books. To order the entire book now along with companion DVDs for the special pre-order price, click here for more information. Aimed at everyone from enterprise developers to self-taught scripters, Real-World AJAX: Secrets of the Masters is the perfect book for anyone who wants to start developing AJAX applications.

Using TinyAjax to Create Live Search
Using a server-side framework will let you shift some of the processing from the client back to the server. In our example we'll consume our Web service using PHP and print out formatted HTML. AJAX will be used to handle the request and the response, but the Web service will be processed on the server. One benefit to this approach is that you can avoid the issues involved with an AJAX cross-domain request.

We'll use TinyAjax for our example, which is a small and unobtrusive library for PHP5. It generates all of the JavaScript necessary for an XMLHttpRequest and gracefully degrades if JavaScript is disabled.

We're going to be using Yahoo's Web Search Service. The API is available from: http://developer.yahoo.com/search/web/V1/webSearch.html.

You'll need to get a free Application ID from the Yahoo! Developer Network to use this example. You can find out more at: http://developer.yahoo.com/faq/#appid.

The Yahoo! Web services are all REST services, and most of them use GET requests. As a result, we'll construct a specially formatted URL to access the service. Our URL will consist of four parts:

  • The Hostname: http://api.search.yahoo.com/
  • The Service Name and Version Number: WebSearchService /V1/
  • The Method: webSearch?
  • The Query Parameters:
    - appid= RWA_LiveYahooSearch
    - &query=SEARCH_TERM
    - &results=10
    - &output=php
Let's take a closer look at the query paramenters. appID specifies the name of our Yahoo! Application ID. The query is the term or terms we will search for. We limit the number of results returned by setting results to 10. We can also specify the format we'd like the response sent in by using the output parameter. Valid options are output=json, output=php, and output=xml. Specifying JSON and XML returns JSON and XML and PHP will return the output in serialized PHP format. Since we're consuming this with PHP on our server, we'll use PHP output.

When we put it all together our URL becomes: http://api.search.yahoo.com/WebSearchService/V1/webSearch?appid=RWA_Live...

If you paste that URL into a Web browser, you'll be prompted to download a file of type "text/php" that contains this:

a:1:{s:9:"ResultSet";a:4:{s:21:"totalResultsAvailable";s:8:"17400000";s:20:"totalR
esultsReturned";i:10;s:19:"firstResultPosition";i:1;s:6:"Result";a:10:{...

If you were to process the response with PHP and use a print_r() function to print the array, you can see the structure of the response. Figure 6.6 shows a snippet of the output from print_r()on the unserialized response.

For a basic live search we only insert the URL in the Result array. We'll loop through $response['ResultSet']['Result'] and print out a list of the titles:

$result = file_get_contents($URL);
$result = unserialize($result);
echo "<ul>";
foreach($result['ResultSet']['Result'] as $r) {
     echo "<li>" . $r['Title'] . "</li>\n";
}
echo "</ul>";

That's about it for our Web service consuming function. Since we're using a server-side framework, there isn't much more to do. We'll create a div to hold output, and a text field to search on. Since we don't want to press a button, we'll set an "onkeyup" hook that will call a JavaScript function generated by TinyAjax.

The TinyAjax Code

Listing 6.13

define('TINYAJAX_PATH', 'include');
require_once(TINYAJAX_PATH . '/TinyAjax.php');
$ajax = new TinyAjax();
$ajax->showLoading();
$ajax->exportFunction("YahooSearch", "search", "#output" );
$ajax->process();

That's it. We include the TinyAjax source file and create a new instance of the object. To show the user that something is happening, we call $ajax->showLoading(), which will display a loading indicator while the callback is in progress.

We pass three arguments to $ajax->exportFunction. The first argument, "YahooSearch," tells Tiny Ajax that when the function "YahooSearch" is called in JavaScript to call the function "YahooSearch" in PHP, YahooSearch() is the name of our function to consume the Web service and TinyAjax automatically creates the JavaScript function for us.

The second argument indicates that it should pass the value of a form field with the ID of "search" as an argument to the YahooSearch() function.

The final argument specifies where to put the output from the PHP YahooSearch() function.

Figure 6.7 shows the results of typing "ajax" with a trailing space to allow a screen capture of the loading indicator while results are displayed.

How to Improve the Example
As mentioned before, this example leaves quite a bit to be desired. Rather than using the onkeyup property, we should put the field in a form, provide a submit button, attach a JavaScript event listener to the input field, and monitor the change event. This concept is called "progressive enhancement" and it's a means of unobtrusively providing a enhanced experience to capable browsers while still leaving a working application for older, less capable browsers. An example of using progressive enhancement and graceful degradation in the real world can be found at http://developer.yahoo.com/yui/articles/gbs/gbs.html.

This content is reprinted from Real-World AJAX: Secrets of the Masters published by SYS-CON Books. To order the entire book now along with companion DVDs, click here to order.

More Stories By Corey Gilmore

Corey Gilmore is the president of CFG Consulting, Inc., specializing in developing rich internet applications with ColdFusion, PHP and Ajax for the Federal government and Fortune 100 clients. He guiltily enjoys designing and implementing low-cost, high performance business continuity plans using VMware ESX server. As the former Director of Information Technology for the United States Senate Democratic Leadership, he designed and implemented a continuity of operations plan to ensure Senate business continuity in the event of a disaster. Corey can be reached at cfgci.com.

More Stories By Jason Blum

Jason Blum is principal engineer with the advanced technologies development team in the United States Senate, Office of the Sergeant at Arms. Formerly the lead administrator of the Senate’s shared Web hosting environment, Jason now designs and manages the implementation of schema and pattern-centric solutions for Senate offices in XML, ColdFusion, Flex, and .NET. He is a Certified Advanced ColdFusion developer with a BA in philosophy, Masters Degrees in philosophy of education and in IT, and an intermediate certification in Hungarian from itk.hu.

More Stories By Phil McCarthy

Philip McCarthy is a UK-based software development consultant
specializing in J2EE and Web technologies. An early adopter of rich
browser-based client development, he has several years' experience of integrating Ajax technologies into enterprise Java frameworks, gained on projects in the financial services, telecoms, and digital media sectors. Philip is also the author of the "Ajax for Java Developers" series for IBM developerWorks, and blogs about software development at chimpen.com.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.