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:

<?php
$html_struct
= array(
    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'
     
),
    array(
     
'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:

<?php
$rand
= rand(0, count($html_struct) - 1);
return
theme_custom_amazon_wishlist_block($html_struct,$rand);
?>

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.

<?php
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&linkCode=as2'.
 
'&camp=1789&creative=9325&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" rel="nofollow"><img alt="" src="$img_src"/></a>
</div>
<div class="awl-item-info">
<h4><a href="$href" title="$title" rel="nofollow">$title</a></h4>
<p>$desc</p>
</div>
<div class="awl-page-link">
<a href="http://www.seo-expert-blog.com/amazon/wishlist" title="Go to my Amazon Wish List, I don't mind if you order something ;)">My Amazon Wish List</a></div>
<img class="affiliate-tracker-img" alt="" src="http://www.assoc-amazon.com/e/ir?t=seoexpertblog-20&l=as2&o=1&a=$asin"/>
</div>
</div>
__EOF__;
}
?>

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);
}

Summary

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.

Sorry, but this article re-invents the wheel (at least in Drupal) and presents bad JS code practices. It also uses extremely slow jQuery selectors that scan the entire document every time. There is a very noticeable delay when changing ads, even though it is simply taking locally cached data and putting it into the existing HTML.

Thanks for your feedback Steven. You are right the selectors are slow, so it's better to wrap a div around the block content that has an ID which can be used in the selectors to speed up things.

What I don't understand is why this code re-invents the wheel in Drupal and whether there are bad JS code practices used apart from the slow selectors.

Hope you tell me more about it.

I updated the code examples, wrapped the ad block in a div with an id, which is used in the jQuery selectors. The book slideshow is now considerably faster, because not the whole DOM tree is parsed every time someone clicks on the previous and next links.

jQuery is to complicated. If less javascript then better.
The example does not work with Konqueror so I suspect you need to update your jQuery source to version 1.1.3.1 which fixed some bugs with Konqueror usage.

You are right I am not using the most current version of jQuery.

Is there some "working example" of your code (some demo)?

Well, yes look at the top of the right sidebar on this site (SEO-Expert-Blog.com). There is a block called "Web Development Books" which uses this code.

Is it possible to use this with items other than Amazon? i.e. Clickbank and/or Commission Junction products?

Yes you can do this with other ads too.

Can I get a copy of that module? I can't quite get my head around your tutorial. Thanks.

All source code is listed here.