... 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.
|
Generate and Collect a Google AJAX Feed API key | |
This key would be useful
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" This code has the following limitations
|
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.
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. |
Positioning the Feed Display | |
• In any Web PageYou 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
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?
|
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.
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. |
Creating the Feed Control (Single Feed Unformatted Result) | |
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).
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.
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.
14. div.appendChild(document.createTextNode(entry.title));
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.
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.
13. var div = document.createElement("div");
15. container.appendChild(div); }
16. } } } ); }
20. google.setOnLoadCallback(initialize);
|
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
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.
• 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.
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.
|
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).
|
Creating the Feed Control (Multiple Feeds Formatted Result) | |
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.
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__);
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.
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
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. |
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
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 | |
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
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 |