XNSIO
  About   Slides   Home  

 
Managed Chaos
Naresh Jain's Random Thoughts on Software Development and Adventure Sports
     
`
 
RSS Feed
Recent Thoughts
Tags
Recent Comments

Fetching Cross Domain XML in JavaScript – Simple Solution

On my latest pet project, SlideShare Presentation Stack, I wanted to make an AJAX call to SlideShare.net to fetch all the details of the given slideshare user. One easy way to get this information is to request for the user’s RSS feed. However the RSS feed is only served as xml. And due to same-origin policy, I can’t make an AJAX call from my javascript to retrive the XML. I wish SlideShare support JSONP for fetching the user’s RSS feed. However they don’t. They do expose an API with rate limiting, but I wanted something simple. I found the following hack to work-around this issue:

<script type="text/javascript">
    simpleAJAXLib = {
        init: function () {
            this.fetchJSON('http://www.slideshare.net/rss/user/nashjain');
        },
 
        fetchJSON: function (url) {
            var root = 'https://query.yahooapis.com/v1/public/yql?q=';
            var yql = 'select * from xml where url="' + url + '"';
            var proxy_url = root + encodeURIComponent(yql) + '&format=json&diagnostics=false&callback=simpleAJAXLib.display';
            document.getElementsByTagName('body')[0].appendChild(this.jsTag(proxy_url));
        },
 
        jsTag: function (url) {
            var script = document.createElement('script');
            script.setAttribute('type', 'text/javascript');
            script.setAttribute('src', url);
            return script;
        },
 
        display: function (results) {
            // do the necessary stuff
            document.getElementById('demo').innerHTML = "Result = " + (results.error ? "Internal Server Error!" : JSON.stringify(results.query.results));
        }
    }
</script>

Trigger the AJAX call asynchronously by adding the following snippet where ever required:

<script type="text/javascript">
      simpleAJAXLib.init();
</script>

How does this actually work?

  • First, I would recommend you read my previous blog which explains how to make JSONP AJAX calls without using any javascript framework or library.
  • Once you understand that, the most important piece you need to understand is how we’ve used Yahoo! Query Language (YQL) as a proxy to retrieve your XML request to be served via JSONP.
  • Use the following steps:
    1. Write a SQL statement like select * from xml where url=’your_xml_returning_url’ and URI encode it.
    2. Append your yql statement to YQL url – https://query.yahooapis.com/v1/public/yql?q=
    3. Finally specify the format as json (ex: format=json) and a callback function name, which will be invoked by the browser once the results are retrieved (ex: callback=simpleAJAXLib.display)
    4. In the callback function, you can access the xml data from this JSON object: query.results

    Licensed under
Creative Commons License