Google AJAX Feed API » Feed Reader

... From 29
Google AJAX Feed API key  
 
To use google API's within a web-site/blog, you need to have an API KEY that is specific to the URL/URI of website/blog.

For the Google Ajax Feed API, you have to generate the key for your website/blog.

There is no wizard to enable you to generate the API key and the application code together. Therefore you need to generate the key, collect the code and use the key within that code.

Move To  

Generate and Collect a Google AJAX Feed API key  
 

This key would be useful

  • For all instances of the use of google AJAX Feed API that you may use on the same web site/blog.
  • For all applications (used within the web site/blog) based on the Google AJAX Feed API.

You can generate the key as many times as you want, but each time a new key would be generated.

Get the Feed Reader Code from the page displaying the API key  
 

There is no wizard to enable you collect the code at a single go.

After clicking the "Generate API Key" button, a page is displayed with the key as well as sample code below it (which uses the same key that is generated).

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title>Google AJAX Feed API - Simple Example</title> <script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAA..."></script> <script type="text/javascript"> google.load("feeds", "1"); function initialize() { var feed = new google.feeds.Feed("http://www.digg.com/rss/index.xml"); feed.load(function(result) { if (!result.error) { var container = document.getElementById("feed"); for (var i = 0; i < result.feed.entries.length; i++) { var entry = result.feed.entries[i]; var div = document.createElement("div"); div.appendChild(document.createTextNode(entry.title)); container.appendChild(div); } } }); } google.setOnLoadCallback(initialize); </script> </head> <body> <div id="feed"></div> </body> </html>

This code has the following limitations

  • It is code for a complete HTML page. Where you wish to use the feed reader as a part of your web page or within a widget, you have to eliminate a part of the code.

    You may copy the code marked above. Ensure the you replace the key.

  • The details relating to the feed displayed are few and the result is displayed is in simple text format.

    Feed Displayed using the Hello World Code
    Feed url: http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/technology/rss.xml

    This uses the google.feeds.Feed class and can download one feed only and display it as unformatted text.

Move To  

Get a more useful Feed Reader Code  
 

<script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAA...Q"></script>
<script type="text/javascript">
google.load("feeds", "1");
function OnLoad() {
   var feedControl = new google.feeds.FeedControl();
   feedControl.addFeed("http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/technology/rss.xml", "BBC News");
   feedControl.addFeed("http://feeds.feedburner.com/Techcrunch", "TechCrunch");
   feedControl.draw(document.getElementById("feedControl"));
}
google.setOnLoadCallback(OnLoad);
</script>
<div id="feedControl">Loading...</div>

If you are collecting the code from a page other than the one that displays your Feed API Key, ensure that the Access Key you generated is used in the code being placed.

Feed Displayed using Customized Code
http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/technology/rss.xml
http://feeds.feedburner.com/Techcrunch

This uses the google.feeds.FeedControl class and can download multiple feeds and can display the result with HTML markup.

Include the code in your blog or web page  
 
To make the feed extract appear in your blog or web page, include the code within the html code of your web page.

If you include the code within a template (like in the case of a blog) then the result would be displayed on all the web pages that are created using that template.

In blogger blog, if you are using the modern widget based template for your blog, you can include (paste) the code within a HTML/Javascript Page Element (widget). This amounts to placing the code in the bog template whereby the result would be displayed on all the pages of the blog.

Move To  

Positioning the Feed Display  
 

• In any Web Page

You can make the feed result appear anywhere on your web page by ensuring the following.

» Reader using the Feed Class

The value of the id attribute for the division that displays the feed result (<div id="feedaha"+>) and the argument supplied in the code [var container = document.getElementById("feedaha");] should be the same.

The division can be placed anywhere you intend on the web page.

» Reader using the FeedControl Class

The value of the id attribute for the division that displays the feed result (<div id="feedsee"+>) and the argument supplied in the code [feedControl.draw(document.getElementById("feedsee"));] should be the same.

The division can be placed anywhere you intend on the web page.

• In a blogger Blog

In blogger blog, if you are using the modern widget based template for your blog, you can position the widget where you want the feed result to appear.

Loading the Ajax Feed API  
 

• STEP 1

<script src="http://www.google.com/jsapi/?key=YOUR-KEY"
      type="text/javascript"></script>
<script type="text/javascript">google.load("feeds", "1");</script>
The first step in the process of creating a custom feed reader on your web page is putting this code in your web page.

This code can be placed within the head section or the body section of the web page.

If you are using the code that is explained above and placing all the code at a single place, it would amount to placing the total code within the body section where you intend the feed result to appear.

» What is it for?

  • <script src="http://www.google.com/jsapi/?key=YOUR-KEY" type="text/javascript"></script>

    This piece of code loads the google.load function, which enables loading individual Google APIs.

    You will have to use the key related to the web-site/blog on which you intend to use the code. Replace YOUR-KEY with the key value.

  • <script type="text/javascript">google.load("feeds", "1") </script>

    This piece of code loads Version 1 (current version) of the feeds API.

    Loading the API requires two steps because Google is moving to a new model of loading AJAX APIs to make it easier to include multiple Google APIs on the same web page.

Creating the Feed Control  
 

• STEP 2 (Last)

Include the script that is in addition to the line of code used for loading the feed api within the web page either in the head or the body section.

You may include the additional code within the same script element used for loading the feed api or within another script element. Whether you format your code in two script elements or three, place the code, as far as possible, along with the other related code, so that you don't lose track of it.

<script type="text/javascript">
google.load("feeds", "1");
function initialize() 
{ 
...
...
</script>
<div id="feeds"> </div>

<script type="text/javascript"> google.load("feeds", "1"); </script>
<script type="text/javascript">
function initialize() 
{ 
...
...
</script>
<div id="feeds"> </div>

If you want to place the divisions that would ultimately hold the feed result elswhere, you may have to consider positioning the divisions as a third step

The script is executed as when it is encountered by the browser. If it is placed within the head section of the web page, it is executed before the body content is loaded.

The code you use (explained below) would be dependent on the type of result you intend to be displayed.

Move To  

Creating the Feed Control (Single Feed Unformatted Result)  
 



01.
02.
03.
04.
05.
06.
07.
08.
09.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
<script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAA..."></script>
<script type="text/javascript">
google.load("feeds", "1");
function initialize() 
{ 
   var feed = new google.feeds.Feed("http://news.nationalgeographic.com/index.rss");
   feed.load(  function(result) 
   {
	if (!result.error) 
	{
		var container = document.getElementById("feed");
		for (var i = 0; i < result.feed.entries.length; i++) 
		{
			var entry = result.feed.entries[i];
			var div = document.createElement("div");
			div.appendChild(document.createTextNode(entry.title));
			container.appendChild(div);
		}
	}
    } );
}
google.setOnLoadCallback(initialize);
</script>
<div id="feeds"> </div>

01. google.load("feeds", "1");
Loads Version 1 (current version) of the feeds API.
02. function initialize() {
A function by name initialize is defined
04. var feed = new google.feeds.Feed("http://news.nationalgeographic.com/index.rss");
google.feeds.Feed, is a class whose constructor is Feed(url).
  • The new operator is called providing it the Constructor with any required arguments as the operand. The new operator
    1. Creates an object without any members, i.e. an empty object
    2. Calls the constructor passing it the arguments as well as a pointer to the empty object created as the "this" pointer.
  • The constructor then initializes the object according to the arguments passed to the constructor.
  • The new operator returns a reference to the object created.

Thus a new object which is an instance of the Feed (or google.feeds.Feed) class is created and the reference to that object (returned by the new operator) is assigned to the variable.

The value of the variable is a reference to the object, not the object itself. Thus, it would not be appropriate to say that the value of the variable is the object. It would be proper to say that the variable refers to the object.

05. feed.load( function(result) {
The feed.load () method calls a callback function passing it a pointer to the result object. The result object holds the data relating to the feed url returned by the google server in the process of creation of the feed object.

A callback function is a function that is called through a function pointer. If you pass the pointer (address) of a function as an argument to another, when that pointer is used to call the function it points to it is said that a call back is made. The anonymous function(result) {...} is the callback function here.

07. if (!result.error) {
A control statement. The block following this is executed if the result.error property has no data related to it, i.e. when the google server returns an error.
09. var container = document.getElementById("feed");
A pointer to the object (HTML element) within the document with the id "feed" is assigned to the variable container so that it can be addressed using the variable name from hereon.
10. for (var i = 0; i < result.feed.entries.length; i++) {
A for loop that executes as many times as there are entries in the result fetched from the google server.
  1. var i = 0; → A variable is declared and initialized for being used to control the loop.
  2. i < result.feed.entries.length; → Condition to check whether to carry on execution or not

    The result.feed.entries.length property holds the numerical value representing the number of entries in the result fetched from the google server.

  3. i++; → Increment the value of i by 1 after each execution.
For one execution of the loop the data relating to one property of one feed entry would be poured into the web page.
12. var entry = result.feed.entries[i];
A pointer to the object holding the entry data is assigned to the variable entry so that it can be addressed using the variable name from hereon.
13. var div = document.createElement("div");
An empty object (html div element node) is created and a pointer to the object is assigned to the variable div so that it can be addressed with the name div from hereon.

Creating an element node would result in the both the opening (<div>) and closing tags (</div>) with no content in between being generated.

Every component of the HTML code in a web page is a Node, or a leaf/branch (tree-like hierarchy). A node can be either an Element Node or a Text Node.

  1. Element nodes are HTML tags (<p>, <img> <div> etc.)

    Element nodes can contain child nodes and attributes within them. For an element node, nodeName is the name of the tag (name="__tagname__") and nodeValue is NULL (value="").

    Each non-empty element node contains a single child text node. All the content within the element node including the text representing the tags of its child elements forms its child text node

  2. A Text Node is a string of text. It cannot contain child nodes or attributes.

    For a text node, nodeName is text (name="text") and nodeValue is the actual text (value="__actual text__").

14. div.appendChild(document.createTextNode(entry.title));
  1. entry.title → The value of the entry object's title property.
  2. document.createTextNode(entry.title) → Create a text node using the value of the entry object's title property.
  3. div.appendChild( ... ); → The text node is appended as a child of the div object.
15. container.appendChild(div); }
The div object (element node) is added as a child to the object by name container (element node)

container is the name of the object that holds the division where you intend the feed to appear on your document.

16. } } } ); }
20. google.setOnLoadCallback(initialize);
A function call that would initialise the execution of the code for creating the feed control.

Since this code is outside any other function, the browser would execute this code i.e. make the function call as and when it is encountered, thereby starting the process of creating the feed control within the web page.

(a). <div id="feeds"> </div>
Position this division where you want the result to be displayed.

You can place the above code and the division at the same place.

• Result from Google Cache

Google has a store (cache) of all the feeds on the web, just like it has a cache of the web pages for its search engine.

The result of the feeds displayed here is from the google server and not directly from the original source. Where there is a time gap between the feed creation and feed caching by the google server, the original feed may give a different result.

We need not need to worry much as this is a possibility only in case of feeds which are updated at short time spans say every half an hour. If in doubt, check the page behind the actual feed url.

• Generating the Output (Multiple Properties)

To make the data relating to multiple properties poured into the web page the above code has to be modified by including an additional loop for the same.


09.
10.
11.
12.
12A.
12B.
12C.
13.
14.
14.
15.
16.
...
		var container = document.getElementById("feed");
		for (var i = 0; i < result.feed.entries.length; i++) 
		{
			var entry = result.feed.entries[i];
			var attributes = ["title", "link", "publishedDate", "contentSnippet"];
			for (var j = 0; j < attributes.length; j++) 
			{
				var div = document.createElement("div");
				div.appendChild(document.createTextNode(entry.title));
				div.appendChild(document.createTextNode(entry[attributes[j]]));
				container.appendChild(div);
			}
		}
...

01. function initialize() {
05. feed.load( function(result) {
07. if (!result.error) {
10. for (var i = 0; i < result.feed.entries.length; i++) {
For one execution of the loop the data relating to two or more (as chosen) properties of one feed entry would be poured into the web page.
12. var entry = result.feed.entries[i];
A pointer to the object holding the entry data is assigned to the variable entry so that it can be addressed using the variable name from hereon.
12A. var attributes = ["title", "link", "publishedDate", "contentSnippet"];
A variable by name attributes is assigned an array of text strings, each of which is the property name relating to a single property within a feed entry.

Refer the JSON column in the list below the data relating to an entry that is available and the property names.

For each iteration of the loop (i.e. for each entry) an inner loop is created that iterates that many times as there are entry properties to be poured into the web page.

12B. for (var j = 0; j < attributes.length; j++) {
A loop that executes as many times as there are entry properties for the entry being handled or processed.
  1. var j = 0; → A variable is declared and initialized for being used to control the loop.
  2. j < attributes.length; → Condition to check whether to carry on execution or not

    The attributes.length property holds the numerical value representing the number of properties in relation to the current entry.

  3. j++; → Increment the value of i by 1 after each execution.
13. var div = document.createElement("div");
14. 14. div.appendChild(document.createTextNode(entry[attributes[j]]));
  1. entry[attributes[j]] → The value of the property being handled in relation to the entry.
  2. document.createTextNode(entry[attributes[j]]) → Create a text node using the value of the property being handled in relation to the entry.
  3. div.appendChild( ... ); → The text node is appended as a child of the div object.
15. container.appendChild(div); }
16. } } } ); }
20. google.setOnLoadCallback(initialize);

Move To  

Configuring the Feed Control (Single Feed Unformatted Result)  
 

• Number of Entries to be displayed

By default the reader displays the result of 4 entries.
04A. feed.setNumEntries(8);
To indicate the number of entries per feed to be displayed, use the setNumEntries( _int_) method, with an integer argument

The method is called using the pointer (variable name) to the object of which it is a member as feed.setNumEntries(8);

• Result Format

By default the feed result format is set to JSON format.
04B. feed.setResultFormat(google.feeds.Feed.MIXED_FORMAT) ;
To set the feed format use the setResultFormat(_format_) method, with the format code as the argument. The arguments can be
  1. google.feeds.Feed.JSON_FORMAT
  2. google.feeds.Feed.XML_FORMAT
  3. google.feeds.Feed.MIXED_FORMAT

The method is called using the pointer (variable name) to the object of which it is a member as feed.setResultFormat(google.feeds.Feed.XML_FORMAT)

• Include Past Entries from the Google Cache

By default, when a feed is loaded, the system returns a cached copy of the specified feed that is 100% in sync with the feed contents at the time that it was cached.
04C. includeHistoricalEntries() ;
To instruct the system to return any additional historical entries that it might have in its cache, call the includeHistoricalEntries() method.
There are no arguments to be passed in calling this method.

Add all these just after the code for creating the feed object and before calling the load() function.

JSON and XML Formats  
 

• This application is not a Pure Feed Reader program

The data representing the feed content is stored on the google servers. It is not being delivered directly from the original feed file. Since the data is provided by google, it is able to provide the data in two different formats XML and JSON, irrespective of the format of the original data.

• XML

XML stands for Extensible Markup Languages. Its primary purpose is to facilitate the sharing of structured data across different information systems

A markup is text combined with tags that provide the understanding on how the text between the tags should be treated. HTML is one best example of a markup language. It combines text with HTML tags making up HTML elements.

XML is classified as an extensible language because it allows its users to define their own tags.

An extensible language is any high-level language that allows its user to modify or enrich its syntax in such a way that a person that does not know the base code cannot tell the customized content from the original.

• JSON

JSON stands for JavaScript Object Notation. It is a lightweight data-interchange format and is easy for humans to read and write as well as for machines to parse and generate.

It is a text format that is completely language independent. It uses conventions that are familiar to programmers of the C-family of languages (like C, C++, C#, Java, JavaScript, Perl, Python, etc.).

The JSON format is often used for transmitting structured data over a network connection in a process called serialization.

In the context of data storage and transmission, serialization is the process of saving an object onto a storage medium (such as a file, or a memory buffer) or to transmit it across a network connection link in binary form. The series of bytes or the format can be used to re-create an object that is identical in its internal state to the original object (actually a clone).

This process of serializing an object is also called deflating or marshalling an object. The opposite operation, extracting a data structure from a series of bytes, is deserialization (which is also called inflating or unmarshalling).

One of the important applications of JSON is in Ajax web applications as an alternative to XML for asynchronous transmission of information between client and server

If we request the result in the JSON format, the feed attribute will be present in the feed result. Where the result is assigned to an object, each item from the data can be extracted using the object name.

Particulars XML JSON
Atom RSS
Feed Title <title> <title> FeedObject.title
Feed Link <link> <link> FeedObject.link
Feed Description <subtitle> <description> FeedObject.description
Feed Author <name>   FeedObject.author
Feed Entries <entry> <item> FeedObject.entries[]
Entry Title <title> <title> EntryObject.title
Entry Link <link> <link> EntryObject.link
Entry Content (1) <content>
<summary>
<description> EntryObject.content
Content Snippet (2)     EntryObject.contentSnippet
Published Date (3) <published> <pubDate> EntryObject.publishedDate
Categories <category> <category> EntryObject.categories[]

Move To  

Code for processing Feed Content returned in XML Format  
 

If result (data) is requested in the XML format, the xmlDocument attribute, a fully parsed XML Document node for the feed, will be present in the feed result.

The document can be accessed using the XML functionality built into browsers (e.g., getElementsByTagName).

<script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAA..."></script>
<script type="text/javascript">
google.load("feeds", "1");
 function initialize() 
{
	var feed = new google.feeds.Feed("http://www.digg.com/rss/index.xml");
	feed.setResultFormat(google.feeds.Feed.XML_FORMAT);
	feed.load( function(result) 
	{
		var container = document.getElementById("feed");
		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 votesElement = google.feeds.getElementsByTagNameNS(items[i], "http://digg.com/docs/diggrss/", "diggCount")[0];
				var votes = votesElement.firstChild.nodeValue;

				var div = document.createElement("div");
				div.appendChild(document.createTextNode(title + " (" + votes + " votes)"));
				container.appendChild(div);
    			}
  		}
	} );
}
google.setOnLoadCallback(initialize);
</script>

Move To  

Creating the Feed Control (Multiple Feeds Formatted Result)  
 



01.
02.
03.
04.
05.
06.
07.
08.
09.
<script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAA..."></script>
<script type="text/javascript">
google.load("feeds", "1");
function initialize() 
{
	var feed = new google.feeds.FeedControl();
	feed.addFeed("http://www.digg.com/rss/index.xml", "Digg");
	feed.addFeed("http://feeds.feedburner.com/Techcrunch", "TechCrunch");
	feed.draw(document.getElementById("feed"));
}
google.setOnLoadCallback(initialize);
</script>
<div id="feed"> </div>

01. google.load("feeds", "1");
Loads Version 1 (current version) of the feeds API.
02. function initialize() {
A function by name initialize is defined
04. var feed = new google.feeds.FeedControl();
google.feeds.FeedControl, is a class whose constructor is FeedControl().

This class enables multiple feed download and includes html format tags within the result.

  • The new operator is called providing it the Constructor. The new operator
    1. Creates an object without any members, i.e. an empty object
    2. Calls the constructor passing a pointer to the empty object created as the "this" pointer.
  • The constructor then initializes the object.
  • The new operator returns a reference to the object created.

Thus a new object which is an instance of the FeedControl (or google.feeds.FeedControl) class is created and the reference to that object (returned by the new operator) is assigned to the variable.

05. feed.addFeed("http://www.digg.com/rss/index.xml", "Digg");
The addFeed method within the object pointed to by the variable feed, adds the url (provided as an argument) to the object and associates it with a section whose header title is the second argument provided.

The feed is not actually loaded until the draw() method is called.

06. feed.addFeed("http://feeds.feedburner.com/Techcrunch", "TechCrunch");
Another url with a relevant label to be used as the header title is added.

Make a call for each of the urls you inted to add.

07. feed.draw(document.getElementById("feed")); }
A pointer to the object (HTML element) within the document with the id "feed" is passed on to the draw() method as argument.

The draw() method within the feed object fetches the result relevant to all the feeds added to the control till that point and appends that as the child text node to the element node passed as argument to it.

They are added to the page gradually as they load, one below the other if they are set to be displayed in a linear mode.

Since the text node also includes all the html formatting tags, a formatted content is displayed as the feed result. The result is made up of the hyper-linked entry title, the author and published date, and the entry's content snippet.

09. google.setOnLoadCallback(initialize);
A function call that would initialise the execution of the code for creating the feed control.

Since this code is outside any other function, the browser would execute this code i.e. make the function call as and when it is encountered, thereby starting the process of creating the feed control within the web page.

(a). <div id="feed"> </div>
Position this division where you want the result to be displayed.

You can place the above code and the division at the same place.

Configuring the Feed Control (Multiple Feeds Formatted Result)  
 

• Number of Entries to be displayed

By default the reader displays the result of 4 entries for each feed.

04A. feed.setNumEntries(5);
To indicate the number of entries per feed to be displayed, use the setNumEntries( _int_) method, with an integer argument

The method is called using the pointer (variable name) to the object of which it is a member as feed.setNumEntries(8);

This setting gets applied to all the feeds.

• Setting the Link Target

By default the links in the feed result are made to open up in the same window.

04B. feed.setLinkTarget(google.feeds.LINK_TARGET_BLANK);
We can alter this by passing an appropriate argument while calling the setLinkTarget() method.

The method is called using the pointer (variable name) to the object of which it is a member as feed.setLinkTarget(__arg__);

  1. google.feeds.LINK_TARGET_BLANK - To open in a new window
  2. google.feeds.LINK_TARGET_SELF - To open in the same window
  3. google.feeds.LINK_TARGET_TOP - To open in the topmost frame
  4. google.feeds.LINK_TARGET_PARENT - To open in the topmost frame or replace the current frame

This setting gets applied to all the links in the feed.

Add all these just after the code for creating the feed object and before calling the load() function.

• Tabbed Display

The feed.draw( ... ) method takes a second optional argument by providing which we can indicate the way the feed content is to be displayed.

03.

06A.
07.
07.
08.
09.
{
...
	var options = {drawMode : google.feeds.FeedControl.DRAW_MODE_TABBED}
	feed.draw(document.getElementById("feed"));
	feeds.draw( document.getElementById("feed"), options);	
}
google.setOnLoadCallback(initialize);

06A. var options = {drawMode: ___ };
A variable holding an array of strings each of which represents an option to be passed on to the draw() method.

As at present there is only one property, drawMode you can choose

  1. drawMode: google.feeds.FeedControl.DRAW_MODE_LINEAR

    This would result in the output being displayed linearly one below the other. This is the default behaviour.

  2. drawMode: google.feeds.FeedControl.DRAW_MODE_TABBED

    This would result in the output being displayed in a tabbed interface. Results of each feed are placed together under a tab. The Label of the tab would be the label argument provided within the addFeed() method.

This argument is optional. If it is not provided, then the content would be displayed linearly.

07. feeds.draw( document.getElementById("feed"), options);
A pointer to the object (HTML element) within the document with the id "feed" is passed on to the draw() method as argument The values stored in the variable options is passed as the second argument.

The draw() method within the feed object fetches the result relevant to all the feeds added to the control till that point and appends that as the child text node to the element node passed as argument to it.

They are added to the page gradually as they load, one below the other if they are set to be displayed in a linear mode.

Since the text node also includes all the html formatting tags, a formatted content is displayed as the feed result. The result is made up of the hyper-linked entry title, the author and published date, and the entry's content snippet.

Move To  

Controlling the Display Format  
 
Where the feeds controlled using the FeedControl() class, the output is emitted includes HTML markup.

The base CSS styling is defined in http://www.google.com/uds/css/gfeed.css which is auto-loaded.

The desired effect can be achieved by defining specific style over-rides.

style properties used in the above illustration

<style type=text/css>

.gfc-control {border:2px double gray; padding:5px; }
.gfc-resultsRoot {border:2px solid tan; padding:5px; margin:2px }
.gfc-resultsHeader {background-color:lavender; padding:5px 0px; }
.gfc-title {font:bold 11pt arial; padding:5px;}

.gfc-results {background-color:ghostwhite; padding:5px 0px; }
.gfc-result {border:2px double navy; padding:5px; margin:5px}

a.gf-title {font:bold 10pt trebuchet ms; text-decoration:underline; padding:5px 0px}
.gf-relativePublishedDate {font:bold 8pt arial; padding:3px 0px}
.gf-snippet {font:8pt verdana; padding:3px 0px}

</style>

Place the style definition code above the javascript code.

While using style properties for modification, make it a habit to check how the result would be displayed in prominent browsers (firefox, ie atleast).

Creating a Feed Search Control  
 



01.
02.
03.
04.
05.
06.
07.
08.
09.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
<script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAA..."></script>
<script type="text/javascript">
google.load("feeds", "1");
var defaultQuery = 'stock markets';  
google.setOnLoadCallback(function() {findFeeds(defaultQuery)});  
function findFeeds(query) 
{
	google.feeds.findFeeds(query, feedSearchDone); 
}
function feedSearchDone(result) 
{
	var el = document.getElementById("feedControl");
	if (result.error || result.entries.length <= 0) 
	{
 		el.innerHTML = '<center>No Results Found</center>';
		return;
	}
	var feedControl = new google.feeds.FeedControl();
	for (var i = 0; i < 4; i++) 
	{
		feedControl.addFeed(result.entries[i].url, result.entries[i].title);
	}
	feedControl.setLinkTarget(google.feeds.LINK_TARGET_BLANK);
	feedControl.setNumEntries(2);
	feedControl.draw(el);
}
function onSubmit() 
{
	inputChange(document.getElementById("input"));
	return false;
}
function inputChange(input) 
{
	var query = input.value.toLowerCase();
	var el = document.getElementById('feedControl');
	el.innerHTML = 'Loading...';
	if (!query) 
	{
		query = defaultQuery;
		input.value = query;
	}
	findFeeds(query);
}
</script>

<form class="search-box" method="post" onsubmit="return onSubmit()">
<input class="search-input" id="input" type="text" 
	size="35" value="Stock Markets"  onchange="inputChange(this)"/>
</form>
<div id=feedControl> </div>

This code can be used to display a search box with the default search result being displayed using the value assigned to the search string within the program code.

01. google.load("feeds", "1");
Loads Version 1 (current version) of the feeds API.
02. var defaultQuery = 'stock markets';
declare a variable by name defaultQuery and assign it a text string
03. google.setOnLoadCallback(function() {findFeeds(defaultQuery)});
pass on defaultQuery as argument to the function findFeeds()
04. function findFeeds(query) {
findFeeds() receives the data in defaultQuery and assigns it to a variable query
06. google.feeds.findFeeds(query, feedSearchDone); }
query is passed on as an argument to the google.feeds.findFeeds() method which fetches the data (feeds related to the query string) and passes it on to the function whose name is given as a second argument to this method
08. function feedSearchDone(result) {
The function feedSearchDone() takes the data (result fetched from the google server) and stores it as an object (assigns it to a variable) by name result.
10. var el = document.getElementById("feedControl");
The HTML element object with the id feedControl is assigned to the variable el so that it can be addressed with that name from hereon.
11. if (result.error || result.entries.length <= 0) {
The code within the block following if (...) will be executed only if there is an error returned (Or) when there are no results returned by the google server. result.error ← result object, error property holds the error data result.entries.length ← result object, entries suobject, length property holds the data indicating the number of entries returned. This would be Zero when there is no data matching the query string.
13. el.innerHTML = '<center>No Results Found</center>';
The inner content of the html object by name el is set to the content within the text string thereby displaying that on the web page.
14. return; }
The control is thereon returned to the calling function return.
Where the above code is not executed i.e. when there are entries returned by the google server the code from hereon will be executed
16. var feedControl = new google.feeds.FeedControl();
A google FeedControl object is created by calling the google.feeds.FeedControl() constructor and is assigned to the variable feedControl so that this object can be accessed using the name feedControl from hereon
17. for (var i = 0; i < 4; i++) {
This loop is set to execute 4 times thereby displaying the entries from the top 4 feeds that it finds relevant to the search query
19. feedControl.addFeed(result.entries[i].url, result.entries[i].title); }
This fetches the content to be displayed from the result object
21. feedControl.setLinkTarget(google.feeds.LINK_TARGET_BLANK);
This sets the link to open in a new window.
22. feedControl.setNumEntries(2);
This sets the number of entries for each feed to be displayed.
23. feedControl.draw(el); }
This finally pours the content on to the web page.
25. function onSubmit() {
This function is called immediately on the reader pressing the enter key after having completed entering the search string in the text box.
27. inputChange(document.getElementById("input"));
This collects the data relating to the html element object by id input (text box where the search string is entered) passing it on as an argument to the inputChange() function.
28. return false; }
This collects the data relating to the html element object by id input (text box where the search string is entered) passing it on as an argument to the inputChange() function.
30. function inputChange(input) {
This function is called immediately on the cursor moving out of the textbox either by pressing the tab key or by clicking elsewhere in the document. This may also be called from within the onSubmit() function.
32. var query = input.value.toLowerCase();
The text string received from the text box is converted to lowercase and assigned to the variable by name query
33. var el = document.getElementById('feedControl');
The HTML element object with the id feedControl is assigned to the variable el so that it can be addressed with that name from hereon
34. el.innerHTML = 'Loading...';
The inner content of the html object by name el is set to the content within the text string thereby displaying that on the web page, till that time data is fetched and poured from the google server
35. if (!query) {
If the query is not empty i.e. in cases other than when the text box has no text
37. query = defaultQuery;
Assign the text string to the variabe defaultQuery
38. input.value = query; }
Change the value of the value argument relating to the text box (input html element with id input) to the data in the variable query
40. findFeeds(query); }
Call the findFeeds() function passing it on the data in the variable query as argument
 

• Code for the Form

01.
02.

03.
<form class="search-box" method="post" onsubmit="return onSubmit()">
<input class="search-input" id="input" type="text" size="35" 
	value="Stock Markets"  onchange="inputChange(this)"/>
</form>

The form is to be included within the web page, preferably near (above or below) the division that would ultimately display the search result as indicated in (33) above [<div id="feedControl"> Loading ... </div>].

01. <form (a) (b) (c) >
A form html form element, used for displaying a text box used for entering/collecting the search string. It has the following attributes
(a) class="search-box"
The class name can be used to define style properties. Using the style properties we can set the formatting options for the form. The form would be a container binding the elements within it.
(b) method="post"
The method to be used by the browser to send the data in the form while submitting it
(c) onsubmit="return onSubmit()
The action to be performed on the "onsubmit" event taking place. Here a function by name onSubmit() is called.
02. <input (a) (b) (c) (d) (e) (f) />
A html input element, i.e. a text box used for entering/collecting the search string. It has the following attributes
(a) class="search-input"
The class name can be used to define style properties. Using the style properties we can set the formatting options for the search box
(b) id="input"
The id assigned to this HTML element. This would be useful in accessing this element using programming code.
(c) type="text"
The type attribute defines the nature of the input element to be displayed on the web page. Value text results in a text box being displayed.
(d) size="35"
The size attribute defines the width of the text box be displayed in terms of number of characters.
(e) value="Stock Markets"
The value attribute defines the text to be displayed in the text box by default
(f) onchange="inputChange(this)"
The onchange attribute defines the action to be performed on the "onchange" event taking place. Here a function by name inputChange() is called passing on the text within the text box as the argument.
03. </form>
(a). <div id=feedControl> </div>
Place the code for the divison where you intend the result to be displayed. The division below or above the form would be appropriate position.
Author Credit : The Edifier ... Continued Page 31

Move To  

♣ Copyright � Krishbhavara. All rights reserved
♣ Site optimized for Internet Explorer 5.5 and above