Thursday, March 13, 2025

Displaying Feed Content using jQuery

Displaying Feed Content using jQuery

Are you looking to present visitors with feed content originating from your own site or from an external provider? In version 1.5, jQuery introduced support for XML parsing, which makes it work with both Atom and RSS feeds without plugins or 3rd party services. In fact jQuery is really all you need to fetch and parse your own feeds. The only limitation is that jQuery cannot read feeds from other domains due to browser cross-domain restrictions. But even that is not a deal breaker as there are a few viable workarounds, including CORS and JSONP. We’ll be taking a quick look at both of those here along with our main order of the day, which is how to display feed contents in the browser using everyone’s favorite JavaScript library, jQuery!

Displaying Feeds from Your Own Website

Many sites display feeds whose content visitors may subscribe to. Showing some sample content from each feed helps visitors to get a taste of that to expect should they subscribe. A little bit of jQuery code is all you need to lookup common feed tags and inject their contents into dynamically created HTML elements. As mentioned in the intro, since version 1.5, jQuery auto-parses XML when using the Ajax-driven $.get() function. Moreover, all of jQuery’s powerful DOM methods that you already know work equally well will XML nodes, allowing you to remove text from the each item and then rewrap it within HTML tags for displaying:

$.get("/feeds/newsfeed.php", function(data) {
    var $XML = $(data);
    $XML.find("item").each(function() {
        var $this = $(this),
            item = {
                title:       $this.find("title").text(),
                link:        $this.find("link").text(),
                description: $this.find("description").text(),
                pubDate:     $this.find("pubDate").text(),
                author:      $this.find("author").text()
            };
        $('#content-div').append($('<h2/>').text(item.title));
        //etc...
    });
});

Displaying Feeds from Other Providers

Unfortunately, Native jQuery cannot display feeds that originate from a different server than your own due to browsers’ same-origin policy on JavaScript. Plugging in a domain other than your own in the code above results in the following error being generated in Firefox’s console:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://anotherdomain.com/feeds/Feed.php. This can be fixed by moving the resource to the same domain or enabling CORS.

The CORS alluded to in the message above is HTTP access control. Using XMLHttpRequest level 2, browsers can make Ajax requests to other domains so long as the target server allows it. A new header called Access-Control-Allow-Origin lets the browser know whether or not it’s okay to make the cross domain request. It can either name a specific site such as

header('Access-Control-Allow-Origin: http://www.some-site.com');

or make make its content accessible to anyone by means of an asterisk:

header('Access-Control-Allow-Origin: *');

Since the Access-Control-Allow-Origin header content is set on the feed server, CORS is not ideal in situations where you don’t have access to that server.

A more promising way to overcome browser same-origin policy limitations is to use JSON with Padding (JSONP). A lot of big sites, including Yahoo! and Google accept requests in JSONP Format. jQuery introduced support for JSONP calls way back in version 1.2. To load JSON data from another domain, specify a JSONP callback, which can be done by appending the callback function name to the query string. In the following example, jQuery automatically replaces the ‘?’ character with a generated function name to call:

jQuery.getJSON(url+"&callback=?", function(data) {
    alert("Prop 1: " + data.prop1 + ", Prop 2: " + data.prop2);
});

Using the Yahoo! YQL API

Let’s move on to a real life example now. I wanted to show the current weather for my home town of Ottawa, Canada, so I went to the Yahoo! YQL Console. It’s a great place to peruse a number of good feeds, including one for the weather! It also lets you construct queries using their YQL language to fetch information from their databases, which is then served up as XML or as a json object.

In the Ajax call, we have to send

  • the name of the json callback parameter, as specified by the YQL service
  • the data type – jsonp
  • a data parameter, which includes the query (q) and the return format
$(document).ready(function() {
  $.ajax({
    url: "http://query.yahooapis.com/v1/public/yql",
    jsonp: "callback",
 
    // tell jQuery we're expecting JSONP
    dataType: "jsonp",
 
    // tell YQL what we want and that we want JSON
    data: {
        q: "use 'http://github.com/yql/yql-tables/raw/master/weather/weather.bylocation.xml' as t_weather;"
         + "select * from t_weather where location='ottawa,canada' and unit='c'",
        format: "json"
    },
    success: function( response ) {
      var channel = response.query.results.weather.rss.channel;
      $('#weather').append($('<h2/>').text(channel.description));
      $.each(channel, function(index, item){
        if (item.description) { $('#weather').append($('<p/>').html(item.description)); }
      });
    }
  });
});

In the success function, the main header is retrieved from the deeply-nested response.query.results.weather.rss.channel.description field and then each item’s description is also appended to our #weather DIV. In this particular case there is only one item, but you should always employ a for loop or jQuery.each() function to retrieve all the items. The description fields, highlighted in this screenshot of the Firefox variable pane, contains HTML-formatted content for easy displaying.

Here is the output of the above code in the browser:

Yahoo! Weather for Ottawa, CA


Current Conditions:
Cloudy, 15 C

Forecast:
Fri – Mostly Sunny. High: 24 Low: 13
Sat – Sunny. High: 28 Low: 13
Sun – Partly Cloudy. High: 28 Low: 14
Mon – Partly Cloudy. High: 27 Low: 14
Tue – AM Clouds/PM Sun. High: 24 Low: 14

Full Forecast at Yahoo! Weather

(provided by The Weather Channel)

Conclusion

Now that we know how to display feed content using jQuery, the next few installments will elaborate on how to use the Yahoo! YQL service to gain the most benefit from it as well as other ways to display cross-domain content.

Rob Gravelle
Rob Gravelle
Rob Gravelle resides in Ottawa, Canada, and has been an IT guru for over 20 years. In that time, Rob has built systems for intelligence-related organizations such as Canada Border Services and various commercial businesses. In his spare time, Rob has become an accomplished music artist with several CDs and digital releases to his credit.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured