| By Corey Gilmore, Jason Blum, Phil McCarthy | Article Rating: |
|
| April 26, 2007 08:00 AM EDT | Reads: |
6,403 |
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,403
Copyright © 2007 SYS-CON Media, Inc. — All Rights Reserved.
Syndicated stories and blog feeds, all rights reserved by the author.
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.
- Cloud Computing on Gartner's Top 10 List and SYS-CON Events' 2010 Calendar
- Confessions of a Ulitzer Addict
- IBM Hardware Chief, Intel VC Exec Arrested in Insider Trading Scam
- My Thoughts on Ulitzer
- Tactical Cloud Computing Panel at 1st Annual GovIT Expo
- Ulitzer.com Named Exclusive "New Media" Sponsor of Cloud Computing Conference & Expo
- Moving Your RIA Apps into the Cloud: Seven Challenges
- Adobe’s Aiming ColdFusion at Multiple Clouds
- Windows 7 – Microsoft’s First Step to the Cloud
- Ulitzer Provides a Powerful Social Journalism Platform
- Jill Tummler Singer, Deputy CIO of CIA, Keynotes at GovIT Expo
- Open Source Mobile Cloud Sync and Push Email
- Practical Approaches for Optimizing Website Performance
- The Difference Between Web Hosting and Cloud Computing
- Cloud Computing on Gartner's Top 10 List and SYS-CON Events' 2010 Calendar
- Ajax in RichFaces 3.3, JSF 2 and RichFaces 4
- Confessions of a Ulitzer Addict
- IBM Hardware Chief, Intel VC Exec Arrested in Insider Trading Scam
- My Thoughts on Ulitzer
- Tactical Cloud Computing Panel at 1st Annual GovIT Expo
- US Post Office Hops a Ride on NetSuite’s Cloud
- Ulitzer.com Named Exclusive "New Media" Sponsor of Cloud Computing Conference & Expo
- WPF Controls by DevExpress
- Moving Your RIA Apps into the Cloud: Seven Challenges
- Building a Drag-and-Drop Shopping Cart with AJAX
- What Is AJAX?
- Google Maps! AJAX-Style Web Development Using ASP.NET
- Flashback to January 2006: Exclusive SYS-CON.TV Interviews on "OpenAjax Alliance" Announcement
- AJAXWorld Conference & Expo to Take Place October 2-4, 2006, at the Santa Clara Convention Center, California
- AJAX Sponsor Webcasts Are Now Available at AJAXWorld Website
- How and Why AJAX, Not Java, Became the Favored Technology for Rich Internet Applications
- "Real-World AJAX" One-Day Seminar Arrives in Silicon Valley
- AJAXWorld University Announces AJAX Developer Bootcamp
- AJAX Support In JadeLiquid WebRenderer v3.1
- Where Are RIA Technologies Headed in 2008?
- Struts Validations Framework Using AJAX





























