Home > Tools > CMS > Drupal > Drupal Hacks > Creating Amazon Ads that Rock with jQuery and PHP

Creating Amazon Ads that Rock with jQuery and PHP

Are you sick of annoying ads that take up large parts of the screen, pop up, under or anywhere else, move around, blink and flash? You want to learn how to create ads that rock with a few lines of simple JavaScript and PHP code? Then let me show you how.

Ads often take up way too much space, are distracting and barely related to the content of a page, which is also true for many so called contextual ad programs. In the worst case you can't even distinguish the actual content from ads.

On the other hand ads are a vital source of income for people or companies who run web sites. Publishing on the web is time consuming and costs money. Even though it can be fun and interesting, it is work, and only few people can afford to work for free.

What kind of Ads to Display

People who come to your web site are usually looking for something specific. Make it easy for them to find it. Let content take up the largest part of the screen and let it be immediately visible without the need to scroll, close pop up windows or layer ads — for me the second most annoying type of ad only surpassed by ads that make noise.

Ads should not be too distracting, so avoid animated banners and the like. Internet marketing gurus will tell you the opposite and many ad providers offer mostly large and animated ads. Why? Because they want your users to click on them, leave your site and come to their sites.

You want users to click on ads too, because you want to make some money from them. The more ad clicks the higher the potential revenue, but only a small part of the ad clicks will result in a sale. The more attention ads attract the more they will be clicked on but the ratio of sales per click will decrease and the number of visitors you loose will increase.

So what kind of ads to use? I recommend unobtrusive text ads and/or static images, that are related to your content and thus can provide some value for your visitors. If that is the case chances rise that ad clicks lead to sales.

Unobtrusive text ads with jQuery and PHP

I'll now show you how I created the Amazon ad block on top of the right sidebar of SEO Expert Blog with jQuery and PHP. I have been publishing on the Web focusing on topics related to Web development for about 7 years. Some years ago I joined the Amazon associate program. Amazon sells books related to the topics I write about. Moreover Amazon is a widely trusted online marketplace and thus a good choice for me.

I selected a number of books about Web development that I either already own or probably will buy myself. I chose the top of the right sidebar because it is clearly visible spot but does not intermingle with the actual content.

To get the source URLs for the images used, the ASINs and the ad code I looked up these books on the Amazon associates web site.

The Data Structure

Now it's time for the code. The data structure used for the product is an array of arrays created in a PHP file, or more exactly in a function that is part of a custom Drupal module I developed for SEO Expert Blog:

= array(
'title' => 'Pro Drupal Development',
'asin' => '1590597559',
'desc' => 'Drupal is a popular content management system you can use to create community-driven sites, including blogs, forums, wiki-style sites, and much more.',
'img_src' => 'http://g-ec2.images-amazon.com/images/I/21XNtR8GHYL._AA_SL110_.jpg'
'title' => 'Pro JavaScript Techniques',
'asin' => '1590597273',
'desc' => 'Pro JavaScript Techniques is the ultimate JavaScript book for the modern web developer by John Resig who created the powerfull JavaScript library jQuery.',
'img_src' => 'http://ec1.images-amazon.com/images/I/21+bR4O5JzL._AA_SL110_.jpg'

Each of the nested arrays contains the book's title, the ASIN, a short description, and the URL to the thumbnail image.

Converting the PHP Array to JavaScript

Drupal provides many useful functions, some of which make handling JavaScript very easy. With drupal_to_js() the PHP array of arrays is converted into a JavaScript array of arrays. With drupal_add_js() this data structure is made available to JavaScript functions used on the pages including the ad block as follows:

drupal_add_js('var awl_items = ' . drupal_to_js($html_struct) .';', 'inline');

The theme_custom_amazon_wishlist_block() functions that generates the HTML code is called with two arguments, the PHP data structure and a pseudo random number, that corresponds to one of the array indices of the data structure. This is to not always display the same book on page loads:

= rand(0, count($html_struct) - 1);

The HTML Output

The theme_custom_amazon_wishlist_block() extracts the data from the book that corresponds to the random index and assigns these values to variables. The HTML code is pretty straightforward. I use a here document to generate it, because here documents supports variable interpolation without the need to escape certain characters all the time.

The HTML returned by this function is displayed in the block when the page is loaded. So far no JavaScript is actually involved, so one of the books will be displayed even if the visitor has turned off JavaScript in the browser.

If you want to use this code you need to replace ASSOCIATEID with your Amazon associate ID.

function theme_custom_amazon_wishlist_block($html_struct, $idx=0) {
$title = $html_struct[$idx]['title'];
$asin = $html_struct[$idx]['asin'];
$desc = $html_struct[$idx]['desc'];
$img_src = $html_struct[$idx]['img_src'];
$href = 'http://www.amazon.com/gp/product/'.
$asin .'?ie=UTF8&tag=ASSOCIATEID&creativeASIN='. $asin;

  return <<<__EOF__
<div id="amazon-book-slideshow">
<div class="item-current" id="item-$idx">
<div class="awl-image">
<a href="$href" title="$title"><img alt="product image" src="$img_src"/></a>
<div class="awl-item-info">
<h4><a href="$href" title="$title">$title</a></h4>
<p>Disclosure: links to Amazon are affiliate links.</p>

The JavaScript

When the document is loaded and JavaScript is enabled in the visitor's browser navigational elements for a book slideshow are added to the block that displays the ads. Instead of using words or graphics I use entities for previous and next links. The two links contain a click handler that calls the function awl_nav() with prev or next as the function's argument:

$('#amazon-book-slideshow div.item-current').append('<a class="awl-nav-prev" href="#" title="Previous" onclick="awl_nav(\'prev\');">&lsaquo;</a>');
  $('#amazon-book-slideshow div.item-current').append('<a class="awl-nav-next" href="#" title="Next" onclick="awl_nav(\'next\');">&rsaquo;</a>');

The awl_nav() function first determines the index of the awl_items array element to display after a visitor clicked on one of the two navigational links. If the visitor clicked on the next link 1 is added to the current index, for the previous link -1 is added. In case the new index is a negative or higher than the highest array index, the new index new_idx is set to the highest or lowest array index respectively.

After the new index is determined the corresponding data is extracted from the awl_items array. The HTML elements to be modified are looked up in the DOM and the values that correspond to the data in the array are replaced with the new data using jQuery objects, selectors and functions.

Note that the jQuery selectors are similar to CSS selectors. If you know CSS and JavaScript you will quickly understand jQuery.

function awl_nav(move) {
  var max = awl_items.length - 1;
  var id_shift = (move == 'prev') ? -1 : 1;
  var idx = $('#amazon-book-slideshow .item-current').attr('id').substr(5);
  var new_idx = parseInt(idx) + parseInt(id_shift);
  if (new_idx == -1) {
    new_idx = max;
  } else if (new_idx == max + 1) {
    new_idx = 0;
  var old_asin = awl_items[idx]['asin'];
  var new_asin = awl_items[new_idx]['asin'];
  var new_href = $('#amazon-book-slideshow div.awl-image a').attr('href').replace(old_asin, new_asin);
  new_href = new_href.replace(old_asin, new_asin);
  var old_tracker_src = $('#amazon-book-slideshow img.affiliate-tracker-img').attr('src').replace(old_asin, new_asin);
  $('#amazon-book-slideshow div.item-current').attr('id','item-'+new_idx);
  $('#amazon-book-slideshow div.awl-image a').attr('href', new_href);
  $('#amazon-book-slideshow div.awl-image a').attr('title', awl_items[new_idx]['title']);
  $('#amazon-book-slideshow div.awl-image a img').attr('src', awl_items[new_idx]['img_src']);
  $('#amazon-book-slideshow div.awl-item-info h4 a').attr('href', new_href);
  $('#amazon-book-slideshow div.awl-item-info h4 a').attr('title', awl_items[new_idx]['title']);
  $('#amazon-book-slideshow div.awl-item-info h4 a').html(awl_items[new_idx]['title']);
  $('#amazon-book-slideshow div.awl-item-info p').html(awl_items[new_idx]['desc']);
  $('#amazon-book-slideshow img.affiliate-tracker-img').attr('src', old_tracker_src);


In this tutorial I demonstrated how unobtrusive ads related to the content can be added to your web pages. With a few lines of PHP and JavaScript code a dynamic product slideshow is created that will attract some but not too much attention.