Search

Dark theme | Light theme

August 2, 2009

Using jQuery's JSONP support to get data from Yahoo! Pipe

In a previous blog entry we learned how to create a Yahoo! Pipe. In this blog entry we will see how we can use jQuery to parse the Yahoo! Pipe's output.

When we run our pipe we have a link Get as JSON. We need the URL of this link so we can use it with our jQuery script. Basically it is the URL of the pipe appended with &_render=json.

Normally we cannot get data from just any domain on the internet with Javascript. But with JSONP we can get data from other domains. jQuery and Yahoo! Pipes supports JSONP, we only have to add &_callback=? to our Yahoo! Pipe JSON URL and we are in business. We use the $.getJSON method to get the data from our pipe. Once we get hold of the data we can use it any way we want. The following code snippet loads the data and then creates a list with the title, link, date and source of the items:

$(document).ready(function() {
    $.getJSON("http://pipes.yahoo.com/pipes/pipe.run?_id=UtVVPkx83hGZ2wKUKX1_0w&_render=json&_callback=?", 
    function(data) {
        $.each(data.value.items, function(idx, item) {
            var listitem = $("<li/>");
            $("<a/>").attr("href", item.link).attr("class", item.source).text(item.title).appendTo(listitem);
            $("<br />").appendTo(listitem);
            $("<span/>").attr("class", "source").text("from " + item.source).appendTo(listitem);
            $("<span/>").text(", " + item.pubDate).appendTo(listitem);
            listitem.appendTo("#activities");  // append to UL element with id activities
        });
    });
});

All put together in a HTML page and a little styling we get the following output:

And here is the complete HTML source:

<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>

  <script>
  $(document).ready(function() {
    $.getJSON("http://pipes.yahoo.com/pipes/pipe.run?_id=UtVVPkx83hGZ2wKUKX1_0w&_render=json&_callback=?",
        function(data) {
          $.each(data.value.items, function(idx,item) {
            var listitem = $("<li/>");
            $("<a/>").attr("href", item.link).attr("class", item.source).text(item.title).appendTo(listitem);
            $("<br />").appendTo(listitem);
            $("<span/>").attr("class", "source").text("from " + item.source).appendTo(listitem);
            $("<span/>").text(", " + item.pubDate).appendTo(listitem);
            listitem.appendTo("#activities");
          });
        });
  });
  </script>
  <style>
    .source { font-style: italic; }
  </style>
</head>
<body>
  <h1>Yahoo! Pipes</h1>
  <ul id="activities">
  </ul>
</body>
</html>