Explore Amazon Web Services with AJAX - LiveSearch - Day 1
Amazon offer access to their database via webservice and this is a great opportunity to explore the different AJAX features that we can implement with it. So as you may understand by Day 1, this week I'll try to focus on the different aspect of using AWS with AJAX using nusoap and prototype. Amazon gives the possibility to retrieve data via REST and SOAP so you can choose the one you want, but I choosed SOAP for the simple reason that I find it very easy to manage with nusoap.
In this first tutorial I choosed a very common usage of AWS which is the Live search. The idea is interesting to implement in your website for example to offer visitors the possibility to search for books, in addition that live search don't take too much place more than the inputbox and a title to explain what is it for.
So to get started you have to create an amazon associates account if you don't have one, then create a web service account. After registring, you'll have an Access Key ID which we'll need to request the web services.
Then download nusoap and prototype.
Now we can start writing our server-side code, which will make remote queries and retrieve answers. As you can see in the screenshot I just displayed the book title, the author(s), ISBN, publisher, price and a picture. The PHP script is listed below :
<?php
/**
* AWS 4.0 with AJAX demos using nusoap and prototype
*
* Author Hatem Ben Yacoub <hatem@php.net>
* http://ajax.phpmagazine.net/
*/
// include nusoap classes
require_once("lib/nusoap.php");
require_once("lib/class.wsdlcache.php");
//------------------------------------------------//
//
// Enter your AWS subscription key here
//
//------------------------------------------------//
$SubscriptionId = '';
//------------------------------------------------//
$AmazonUS = 'http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl';
function GetItemSearchParams($Keywords) {
global $SubscriptionId;
$request = array(
"Keywords" => $Keywords,//"AJAX",
"SearchIndex" => "Books",
"ResponseGroup" => "Medium"
);
$itemSearch = array(
'SubscriptionId' => $SubscriptionId,
'AssociateTag' => 'phpmagazine-20',
'Request' => $request
);
return $itemSearch;
}
// Setting the WSDL
$wsdlurl = $AmazonUS;
// Try getting data from cache
$cache = new wsdlcache('cache', 120);
$wsdl = $cache->get($wsdlurl);
if (is_null($wsdl)) {
$wsdl = new wsdl($wsdlurl);
$cache->put($wsdl);
} else {
$wsdl->debug_str = '';
$wsdl->debug('Retrieved from cache');
}
$client = new soapclient($wsdl,true);
$client->soap_defencoding = 'UTF-8';
$result = $client->call('ItemSearch', array('body' => GetItemSearchParams($_GET['Keywords'])));
if (is_Array($result['Items']['Item'])) {
$display = '';
foreach($result['Items']['Item'] as $item) {
$author = (is_array($item['ItemAttributes']['Author']))?@implode(', ',$item['ItemAttributes']['Author']):$item['ItemAttributes']['Author'];
$display .= "<div class=item>
<h2><a href=\"".$item['DetailPageURL']."\">".$item['ItemAttributes']['Title']."</a></h2>
<a href=\"".$item['DetailPageURL']."\"><img src=\"".$item['SmallImage']['URL']."\" width=\"".$item['SmallImage']['Width']['!']."\" height=\"".$item['SmallImage']['Height']['!']."\" align=\"right\" border=0></a>
<ul>
<li><strong>ISBN :</strong> ".$item['ItemAttributes']['ISBN']." </li>
<li><strong>Author(s) :</strong> ".$author."</li>
<li><strong>Publisher :</strong> ".$item['ItemAttributes']['Publisher']."</li>
<li><strong>Price: </strong> <font color=red style='text-decoration: line-through;'>".$item['ItemAttributes']['ListPrice']['FormattedPrice']."</stroke></font> <font size=+2>".$item['OfferSummary']['LowestNewPrice']['FormattedPrice']."</font></li>
</ul>
</div><br/>\n";
}
} else {
$display = "<div class=item><font color=red>No result available for <strong>".$_GET['Keywords']."</strong></font></div>";
}
echo $display;
exit;
?>
The script will simply get the keywords from GET method so we can request dynamicly from javascript. The Javascript will observe the inputbox with the id Keywords, and for every event KeyUp it trigger an AJAX request to retrieve data from the previous script.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>AJAX Amazon demo - Live Book search</title>
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript" src="effect.js"></script>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<script>
Event.observe(window, 'load', init, false);
function init(){
Event.observe('Keywords', 'keyup', livesearch , false);
}
function livesearch(){
var url = 'proxy.php';
var pars = 'Keywords='+escape($F('Keywords'));
var target = 'result';
var myAjax = new Ajax.Updater(
target,
url,
{
method: 'get',
parameters: pars,
onComplete:function(request){Element.hide('search_spinner')},
onLoading:function(request){Element.show('search_spinner')},
onFailure: reportError
});
}
function reportError(request)
{
alert('Sorry. There was an error.');
}
</script>
<form method="get" action="proxy.php" id="greeting-form">
<div class="item">
<label for="Keywords">Search amazon books :</label>
<input id="Keywords" type="text" size="64" />
<img alt="Spinner" id="search_spinner" src="spinner.gif" style="display:none;" />
</div>
</form>
<br/>
<div id="result"></div>
</body>
</html>
There is two ways to make AJAX request with prototype using Ajax.Request and then setting the onComplete: showResponse event fonction with the showResponse() the function that prototype will run after completing request data from server. And depending if you want to use the result as xml to parse it with Javascript or display it directly in the page you can use responseXML or responseText :
function showResponse(originalRequest)
{
// get the response as text
var result = originalRequest.responseText;
// get the response as xml
//var resultxml = originalRequest.responseXML;
}
Now the script is done you can see it working online. You can play with the script and display for examples title of the book, link and the current price only see demo 2. This will be also an excellent alternative for people looking to monetize their website, by offering more dynamic ways to find products more easily.
Conclusion
This script is maybe the most simple and classic thing we can do with AWS, i wanted to began with it to introduce using AJAX with Amazon Web Services. We'll see more demos later, so if you have questions or suggestions you can drop me a message.
Update : Download code of this demo


Subscribe to AJAX Magazine's feed