Amazon Wish List In JSON

Today I explored some alternative JavaScript coding methods to make it easier to dynamically create DOM elements. I used jQuery and the jQuery Plugin, FlyDOM, to work with the Amazon web service API. I bought the book Amazon.com Mashups by Francis Shanahan from the Computer Books Direct club which is closing and selling books cheap. I have not read the book yet but there is a chapter on converting Amazon data directly into JSON using XSLT (hmm, interesting) and it actually covers several other APIs and the technology behind mashups. There was some mention of Amazon wish lists which attracted my attention because I use wish lists to save books that I come across which I may want to buy some day. In other words, this is personal data that I am actually interested in.

My goal was to find a better way to generate dynamic content. Using the DOM functions createElement(), createTextNode(), and appendChild() was getting to be a tedious chore. When you throw in attributes that can be set with the setAttribute() function, you wind up with 3 or 5 lines for every HTML tag. Even a bold tag requires a lot more code than it is worth. Fortunately, jQuery with the FlyDOM plugin can reduce this code to a single line to create a single tag. 

Amazon Wish List

Here are some things to note about the code:

  1. Using a jQuery plugin is just a matter of pulling in an additional file of JavaScript.
  2. You need to sign up for an Amazon Access Key and there is a small fee for using their web services.
  3. The query string in the web address for the web service had a lot of ampersands which I replaced with the | character. I'm still using my xml2json generic handler.
  4. FlyDOM allows you to create a table using JSON syntax. This isn't very easy but it is good practice.
  5. No sample code was provided for dynamically creating table rows in a loop. I imagine you could do it better by treating it as an array expressed in JSON.
  6. Troubleshooting dynamically generated DOM elements is difficult because viewing the source doesn't show you anything. This is where Nikhil Kothari's Web Development Helper proves to be invaluable because it has a DOM Inspector that reveals the dynamically generated elements.

 The table below the DIV was dynamically generated and will not appear in the HTML source view.

DOM Inspector

<script type="text/javascript">
// repeatedly calls AddScript until there is an object
var intAttemptCount = 0;
function LoadJSON() {
AddScript();
while (typeof(obj) == "undefined") {
AddScript();
if (intAttemptCount == 10) return;
}
DisplayWishList();
}
function AddScript() {
        jscript = document.createElement("script");
jscript.setAttribute("type", "text/javascript");
jscript.setAttribute("src", http://localhost/rss2json/xml2json.ashx?feed=http://webservices.amazon.com/onca/xml?Service=AWSECommerceService|Version=2006-06-07|AWSAccessKeyId=00000000000000000000|Operation=ListLookup|ListType=WishList|ListId=12S9629PIWFHP|Sort=DateAdded|ResponseGroup=ItemAttributes,ListItems,ListInfo,Images);
document.getElementsByTagName('head')[0].appendChild(jscript);
intAttemptCount = intAttemptCount + 1;
alert("Attempt #"+intAttemptCount);
}
function DisplayWishList() {
//    for (prop in obj.ListLookupResponse.Lists.List.ListItem[0]) {
//        alert(prop);
//    }
//    return;
    // dynamically create DOM elements 
    $(document).ready(function(){
        // create table and header row
        $('#response').createAppend(
            'table', { width: '500px', className: 'tableData', id: 'Amazon' }, [
                'tr', { }, [
                    'th', { align: 'center' }, 'Amazon.com Wish List - ' + obj.ListLookupResponse.Lists.List.ListName
                           ]
               ,'tr', { }, [
                'td', { align: 'left', id: 'info', style: 'font-size: 10pt;' }
                           ]            
            ]
        );
        $('#info').createAppend('b', { }, 'Customer Name: ');
        $('#info').append(obj.ListLookupResponse.Lists.List.CustomerName);
        $('#info').createAppend('br', { });
        $('#info').createAppend('b', { }, 'Date Added: ');
        $('#info').append(formatDate(obj.ListLookupResponse.Lists.List.DateCreated));
        $('#info').createAppend('br', { });
        $('#info').createAppend('b', { }, 'Total Items: ');
        $('#info').append(obj.ListLookupResponse.Lists.List.TotalItems);
        $('#info').createAppend('br', { });
        $('#info').createAppend('b', { }, 'Total Pages: ');
        $('#info').append(obj.ListLookupResponse.Lists.List.TotalPages);
        // loop through items
        for (var i = 0; i < obj.ListLookupResponse.Lists.List.ListItem.length; i++) {
            // create table row
            $('#Amazon').createAppend(
                'tr', { }, [
                'td', { align: 'left', id: 'book' + i, style: 'font-size: 10pt' }
                          ]
            );
            $('#book' + i).createAppend('img', { src: obj.ListLookupResponse.Lists.List.ListItem[i].Item.SmallImage.URL, align: 'left', hspace: '5', height: obj.ListLookupResponse.Lists.List.ListItem[i].Item.SmallImage.Height.value, weight: obj.ListLookupResponse.Lists.List.ListItem[i].Item.SmallImage.Width.value }, null);  
            $('#book' + i).createAppend('a', { href: obj.ListLookupResponse.Lists.List.ListItem[i].Item.DetailPageURL }, obj.ListLookupResponse.Lists.List.ListItem[i].Item.ItemAttributes.Title);
            $('#book' + i).createAppend('br', { });
            $('#book' + i).append('by ' + obj.ListLookupResponse.Lists.List.ListItem[i].Item.ItemAttributes.Author);
            $('#book' + i).createAppend('br', { });
            $('#book' + i).createAppend('b', { }, 'Price: ');
            $('#book' + i).append(obj.ListLookupResponse.Lists.List.ListItem[i].Item.ItemAttributes.ListPrice.FormattedPrice);
            $('#book' + i).createAppend('br', { });
            $('#book' + i).createAppend('b', { }, 'Binding: ');
            $('#book' + i).append(obj.ListLookupResponse.Lists.List.ListItem[i].Item.ItemAttributes.Binding);
            $('#book' + i).createAppend('br', { });
            $('#book' + i).createAppend('b', { }, 'ISBN: ');
            $('#book' + i).append(obj.ListLookupResponse.Lists.List.ListItem[i].Item.ItemAttributes.ISBN);
            $('#book' + i).createAppend('br', { });
        }
    });
    return;     
}
/**
* Converts date from UTC string format (e.g "2003-10-01T00:30:52Z") to JavaScript Date object.
* param String with date to convert.
* return Date object initialized from string.
*/

function utcStringToDate(string)
{
    var date = new Date();
    date.setUTCFullYear(string.substr(0,4));
    date.setUTCMonth(string.substr(5,2)-1);
    date.setUTCDate(string.substr(8,2));
    return date;
}
// this function reformats the date
function formatDate(string) {
    var date = utcStringToDate(string);
    return date.toLocaleDateString();
}
</script>

No Comments