Amazon Associates & AWS - PHP5 and jQuery

Work in progress

Part #1 - Search engine

Enter Title keywords and press the Return key (US books only).

Examples : xml, jquery, php 5, perl

PHP5 Source code

Basicaly, this script builds the SOAP Query array, instanciate a Soap client with various options, place a call to Amazon Web Service and return the data.
Note: You must be registered with Amazon web services (AWS) to use this script.


<?
define('SITE_ROOT', $_SERVER['DOCUMENT_ROOT']);

/**
 * I set up a cronjob to update this one every hour (see below)
 */
$wsdl_path = SITE_ROOT . '/path/cache/AWSECommerceService.wsdl';

$subscription_id = '<your AWS subscription id>';

/**
 * The best pratice here would be to sanitize the keywords
 */
$search_query 	= array(
                 'SubscriptionId' => $subscription_id,
                 'AssociateTag'   => 'moblurorg-21',
                 'Request'        => array(
                                         "Title"         => $_GET['keywords'],
                                         "Count"         => $_GET['count'],
                                         "SearchIndex"   => "Books",
                                         "ResponseGroup" => "Medium"
                                ),
                   );

/**
 * PHP5 SoapClient initialization
 */
$c = new SoapClient($wsdl_path, array(
	'encoding'=>'UTF-8', 
	'compression' => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP
	)
);

/**
 * Calling the Soap method
 */
$result = $c->__call('ItemSearch', array('body' => $search_query));

/**
 * If there's any error, return it using json_encode()
 */
if(is_object($result->Items->Request->Errors->Error)) {
	print json_encode($result->Items->Request->Errors->Error);
	
} 
else {
	/**
	 * No error, returning the whole php object as Json data using json_encode()
	 */
	if(is_array($result->Items->Item)) {
		print json_encode($result->Items->Item);
	}
}
?>

Minimum xHTML


<input type="text" name="keyword" value="" id="keyword"/>
<span id="waiter" style="display:none;">
   <img src="ajax-loader-small.gif" style="border: none;" alt="loading..."/>
</span>

<div id="container"></div>

Minimum CSS 2.0


#container {
	text-align: center;
	width: 100%;
}
.book {
	float:left;
	text-align:center;
	width:30%;
	height:200px;
}

Javascript - jQuery Source code


function get_books(options) {

 var defaults = {
  'keywords'   : '',
  'max_items'   : 3,
  'debug'    : true
 };
 
 if(options.keywords && options.keywords.length > 0) {
 
  /** 
   * Setting unsetted options to defaults
  */
  for (var o in defaults) {
   if(!options[o] || options[o] == undefined) {
    options[o] = defaults[o];
   }
  }
  
  /** 
   * jQuery Ajax
  */
  $.ajax(
   {
    type:   'GET',
    url:   'service.php?keywords=' + options.keywords + '&count=' + options.max_items,
    cache:  false,
    dataType: 'json',
    success:  function(json){
         /** 
          * We've got an error from AWS, displaying it.
         */
         if(json['Message'] != undefined) {
          $("#container").html(' ');
          $("#container").append('<p>'+json['Message']+'</p>');
          return;
         } 
         else {
          /** 
           * Trimming results to minimum from ever options 
           * or AWS answer, wichever is the lesser 
          */
          var stop_at = Math.min.apply({},[options.max_items, json.length-1]);

          /** 
           * Looping through records
          */
          for (var i in json) {
           i = parseInt(i);
           /** 
            * This is a new search, reseting the container
           */
           if(i == 0) {$("#container").html(' ');}

           /** 
            * The item has image informations
           */
           if(typeof(json[i]['SmallImage']) == 'object') {
            var img_url = json[i]['SmallImage']['URL'];
            var img_w  = json[i]['SmallImage']['Width']['_'];
            var img_h  = json[i]['SmallImage']['Height']['_']
           }
           else {
            /** 
             * Default image settings
            */
            var img_url = '/public/no-img.gif';
            var img_w  = 60;
            var img_h  = 40;
           }
           
           /** 
            * Appending result to the container
           */
           $("#container").append('<p class="book"><a href="'+json[i]['DetailPageURL']+
              '"><img src="'+ img_url +'" width="'+img_w+'" height="'+img_h+
              '" alt="'+ json[i]['ItemAttributes']['Title'] + '"/></a><br/>by '+
              json[i]['ItemAttributes']['Author'] + ' - ' + json[i]['ItemAttributes']['Title']+
              '</p>');
           
           /** 
            * Safely closing our display if stop's reached
           */
           if(i == stop_at) {
              $("#container").append('<div style="clear:both;"></div>');
              return;
           }
          }
          
         }
        }
   }
  );
 } 
}

$(document).ready(function() {
 
 /** 
  * Displaying the 'Ajax web2.0 waiter' during AWS calls
 */
 $("#waiter").ajaxStart(function(){
  $(this).show();
 }).ajaxComplete(function(){
  $(this).hide();
 });

 /** 
  * The fonction is triggered each time the input receive the keycode 13 (return)
 */
  $('#keyword').bind('keyup', function(e) {
   if(parseInt(e.keyCode) == 13) {
    get_books({'keywords': $('#keyword').attr('value')});
   }
  });

});

Appendix - Cronjob

The content of "http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl" will be saved as /path/cache/AWSECommerceService.wsdl every hour at 05 minutes.


#5 * * * * wget -q -O /path/cache/AWSECommerceService.wsdl \ 
http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl

Add a comment

HTML code is displayed as text and web addresses are automatically converted.

Please, feel free to contact me if you have any question or comment about this page | Syntax coloration powered by Chili

eXTReMe Tracker