Motyar

@motyar

Freelance Web Developer

Static Web Hosting, made easy

Jan 7, 2010

show your blog feeds on web with YQL and JS

Web is your database these days. yes its so; Flickr stores photos for us and even allows us to edit them online. YouTube does almost the same with videos, LinkedIn allows us to maintain our CV, Delicious our bookmarks and so on.

All of these services also provide ways to use the data in the form of Application Programming Interfaces, or APIs for short. APIs give us data in desired format on our requests.

The problem is that every API has a different way.

YQL allows us to access web services and even the data embedded in web documents in a simple fashion – SQL style- like-

Select * from the web and filter it the way you want

I am here with you; trying to demonstrate this useful thing(YQL) with an example to access a rss feed of my blog.

The Html


<h1><a href="http://motyar.blogspot.com">My Blog</a></h1>
<ul id="feeds">  
</ul>

The feed ul is the target div where we have to show the feeds.

The Javascript

var x = document.getElementById('feeds');
if(x){

url = "http://motyar.blogspot.com";

var yql = 'SELECT title,link,description FROM feed where url in (select href from html where url in ("'+url+'") and xpath="//link[contains(@type,\'rss\')][1]")';

var api = 'http://query.yahooapis.com/v1/public/yql?q='+encodeURIComponent(yql)+'&format=json&callback=showresults';

var s = document.createElement('script');
s.setAttribute('src',api);
document.getElementsByTagName('head')[0].appendChild(s);
}

function showresults(o){
var items = o.query.results.item;
var c = 0;
var out = '';
for(var i=0,j=items.length;i<j;i++){

out += '<li><a href="'+items[i].link+'">'+items[i].title+'</a>';
out += '</li>';

}

x.innerHTML = out;

}

Yql fetches data in our desired format (that is json here). the function showresults is the callback function that parses the json and shows it in html format.

Demo

You can see it in action here

Related posts
parsing html with Yql and php without regular expressions
Call api with javascript without using ajax

Labels: ,




By :