Friday, May 4, 2007

Programming Mashups using Google Ajax Feeds API -- Part 2 of 2

Deviating from default:
In the previous part we learned how to pull a feed into a mashup using bare bones of the AJAX feed API.In this part we will see what customization is possible in the API and how !!

Things That can be changed:

  • Number of entries in default pulling is 4, this can be changed
  • Result format by default is JSON, this can be changed to XML
Changing Number Of Entries:
This can be changed by calling setNumEntries method of feed object. the argument of this methods is number of entries you wanna pull in each result object. This is a important method and would come in handy in almost all mashup programming.


This method should be called before calling load.

Changing Result Format:
Like Number of entries this can also be changed by calling a method on the feed object, Method of interest in this regard is setResultFormat(format). Format can take one of the three values

1> google.feeds.Feed.JSON_FORMAT (default)
2> google.feeds.Feed.XML_FORMAT
3> google.feeds.Feed.MIXED_FORMAT


Example Mashup:
In this example we will try to use all the concepts learned till now, This will contain a mashup of 2 feeds, one pulled as JSON and other pulled as XML. More of number of entries will also be different in both the feeds. This should suffice the usage of all API's present in the armour.

Function to pull a feed with result in JSON format:

function pull_json(feed_url,container_id,num_entries)
var feed = new google.feeds.Feed(feed_url);
feed.load(function(result) {
if (!result.error) {
var feed_container = document.getElementById(container_id);
for (var i = 0; i <= result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var div = document.createElement("div");
var link = document.createElement("a");;

Function to pull a feed with result in XML Format:

function pull_xml(url,container_id,entries)
var feed = new google.feeds.Feed(url);
feed.load(function(result) {
var feed_container = document.getElementById(container_id);
if (!result.error) {
var items = result.xmlDocument.getElementsByTagName("item");
for (var i = 0; i < items.length; i++) {
var titleElement = items[i].getElementsByTagName("title")[0];
var title = titleElement.firstChild.nodeValue;
var linkElements = items[i].getElementsByTagName("link")[0];
var link_url = linkElements.firstChild.nodeValue;
var descElements = items[i].getElementsByTagName("description")[0];
var desc = descElements.firstChild.nodeValue;
var div = document.createElement("div");

var link = document.createElement("a");

div.appendChild (link);


Full Source with minimal layout can be found here
Sample Demo Of above mashup can be viewed here

Mashup programming is made easy by Google AJAX Feed API, and we learned how !! This 2 article series covered the API with examples and I will soon put a cool sample mashup using google AJAX API as soon as I get time.

No comments: