| By Corey Gilmore, Jason Blum, Phil McCarthy | Article Rating: |
|
| April 26, 2007 08:00 AM EDT | Reads: |
6,158 |
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
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.
Published April 26, 2007 Reads 6,158
Copyright © 2007 SYS-CON Media, Inc. — All Rights Reserved.
Syndicated stories and blog feeds, all rights reserved by the author.
About 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.
About 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.
About 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.
- "Virtualization Is Now a Key Strategic Theme," Says Citrix CTO
- Are you Application vAvailable?
- Cloud Computing Expo Europe 2009 in Prague: Themes & Topics
- Cloud Computing Expo 2009 West: Call for Papers Deadline July 15
- Cloud Computing Casts Shadow on Walled Gardens
- An A to Z of Cloud Computing Companies in 2009
- Virtualization Conference & Expo 2009 West: Call for Papers Closing
- Virtualization Conference Europe 2009: 18-19 May 2009 in Prague
- We Will Make the Cloud Hype a Reality: VMware CTO
- Ulitzer’s Amazing First 30 Days in Public Beta
- "Virtualization Is Now a Key Strategic Theme," Says Citrix CTO
- Are you Application vAvailable?
- Cloud Computing Expo Europe 2009 in Prague: Themes & Topics
- Cloud Computing Expo 2009 West: Call for Papers Deadline July 15
- SYS-CON's 5th International Virtualization Conference & Expo: Themes & Topics
- Cloud Computing Casts Shadow on Walled Gardens
- An A to Z of Cloud Computing Companies in 2009
- Citrix CEO "The Industry Needs Time"
- Virtualization Conference & Expo 2009 West: Call for Papers Closing
- Virtualization Conference Europe 2009: 18-19 May 2009 in Prague
- FullArmor GPAnywhere Secures Microsoft Application Virtualization Applications Through Group Policy
- SYS-CON's Virtualization Conference & Expo: Themes & Topics
- SYS-CON's Virtualization Journal Opens Its "Readers' Choice Awards" Nominations
- Application Virtualization: Instant Migration to Vista, Fast Delivery, Secure Access, Side-by-Side Deployments
- Integration with Windows Vista, Microsoft Excel, and Microsoft Application Virtualization
- "Virtualization Is Now a Key Strategic Theme," Says Citrix CTO
- mValent Extends Automated Application Configuration Management to Virtualization Environments
- Will Microsoft Buy Citrix?
- Are you Application vAvailable?
- Virtualization Conference Keynote Webcast Live on SYS-CON.TV







































