YUI 3.x Home -

YUI Library Examples: IO: XML Transaction — Retrieving a Yahoo! Weather RSS (XML) Feed via a Server-Side Proxy

IO: XML Transaction — Retrieving a Yahoo! Weather RSS (XML) Feed via a Server-Side Proxy

This example demonstrates how to use IO and a PHP proxy — to work around XMLHttpRequest's same-domain policy — to retrieve an XML document from http://xml.weather.yahoo.com/forecastrss.

To try out the example, fill in your five-digit US zip code, or Location ID.

Please enter a U.S. Zip Code or a location ID to get the current temperature. The default is Zip Code 94089 for Sunnyvale, California; its location ID is: USCA1116.

Exploring the Code for This Example

Create a YUI instance, using IO, for this example:

  1. //Create a YUI instance including support for IO:
  2. YUI({base:"../../build/", timeout: 10000}).use("io-base", function(Y) {
  3. // Y is the YUI instance.
  4. // The rest of the following code is encapsulated in this
  5. // anonymous function.
  6. } );
//Create a YUI instance including support for IO:
YUI({base:"../../build/", timeout: 10000}).use("io-base", function(Y) {
	// Y is the YUI instance.
	// The rest of the following code is encapsulated in this
	// anonymous function.
} );

Callback Object and the Weather RSS

Yahoo! Weather RSS will return an XML document if the transaction is successful. The following success callback handlers is used to process the response.

  1. //Define a function to handle a successful response from
  2. //Yahoo! Weather. The success handler will find the response
  3. //object in its second argument:
  4. function successHandler(id, o){
  5. Y.log("Success handler called; handler will parse the retrieved XML and insert into DOM.", "info", "example");
  6. var root = o.responseXML.documentElement;
  7. var oTitle = root.getElementsByTagName('description')[0].firstChild.nodeValue;
  8. var oDateTime = root.getElementsByTagName('lastBuildDate')[0].firstChild.nodeValue;
  9. var descriptionNode = root.getElementsByTagName('description')[1].firstChild.nodeValue;
  10.  
  11. div.set("innerHTML", "<p>" + oTitle + "</p>" + "<p>" + oDateTime + "</p>" + descriptionNode);
  12.  
  13. Y.log("Success handler is complete.", "info", "example");
  14. }
//Define a function to handle a successful response from
//Yahoo! Weather.  The success handler will find the response
//object in its second argument:
function successHandler(id, o){
    Y.log("Success handler called; handler will parse the retrieved XML and insert into DOM.", "info", "example");
    var root = o.responseXML.documentElement;
    var oTitle = root.getElementsByTagName('description')[0].firstChild.nodeValue;
    var oDateTime = root.getElementsByTagName('lastBuildDate')[0].firstChild.nodeValue;
    var descriptionNode = root.getElementsByTagName('description')[1].firstChild.nodeValue;
 
    div.set("innerHTML", "<p>" + oTitle + "</p>" + "<p>" + oDateTime + "</p>" + descriptionNode);
 
    Y.log("Success handler is complete.", "info", "example");
}

Assemble the Querystring and Initiate the Transaction

The Yahoo! Weather RSS feed requires a simple HTTP GET request with a base URL and a querystring containing the required information as a name-value pair. In this example, we will use the following parameter:

  • p — location as U.S. Zip Code or Location ID

The following are some example location IDs (do not include the city name):

  • Beijing: CHXX0008
  • Helsinki: FIXX0002
  • London: UKXX0085
  • Moscow: RSXX0063
  • Munich: GMXX0087
  • Paris: FRXX0076
  • Riyadh: SAXX0017
  • Tokyo: JAXX0085

For more details on the Yahoo! Weather RSS feed and other location IDs, please visit http://developer.yahoo.com/weather/index.html.

Function getModule retrieves the input values for location and creates a querystring:

  1. //When the Get RSS button is clicked, this function will fire
  2. //and compose/dispatch the IO request:
  3. function getModule(){
  4. //Get the input value:
  5. var iZip = Y.Node.get('#zip').get("value");
  6.  
  7. //Create a querystring from the input value:
  8. var queryString = encodeURI('?p=' + iZip);
  9.  
  10. //The location of our server-side proxy:
  11. var entryPoint = '(assets/)weather.php';
  12.  
  13. //Compile the full URI for the request:
  14. var sUrl = entryPoint + queryString;
  15.  
  16. Y.log("Submitting request; zip code: " + iZip, "info", "example");
  17.  
  18. //Make the reqeust:
  19. var request = Y.io(sUrl, {
  20. method:"GET",
  21. on:
  22. {
  23. success:successHandler,
  24. failure:failureHandler
  25. }
  26. }
  27. );
  28. }
  29.  
  30. //Use the Event Utility to wire the Get RSS button
  31. //to the getModule function:
  32. Y.on("click", getModule, "#getWeather");
//When the Get RSS button is clicked, this function will fire
//and compose/dispatch the IO request:
function getModule(){
    //Get the input value:
    var iZip = Y.Node.get('#zip').get("value");
 
    //Create a querystring from the input value:
    var queryString = encodeURI('?p=' + iZip);
 
    //The location of our server-side proxy:
    var entryPoint = '(assets/)weather.php';
 
    //Compile the full URI for the request:
    var sUrl = entryPoint + queryString;
 
    Y.log("Submitting request; zip code: " + iZip, "info", "example");
 
    //Make the reqeust:
    var request = Y.io(sUrl, {
        method:"GET",
        on:
            {
                success:successHandler,
                failure:failureHandler
            }
        }
    );
}
 
//Use the Event Utility to wire the Get RSS button
//to the getModule function:
Y.on("click", getModule, "#getWeather");

Full Script Source

Here is the full JavaScript source for this example:

  1. YUI({base:"../../build/", timeout: 10000}).use("io",
  2.  
  3. function(Y) {
  4.  
  5. //Get a Node reference to the div we'll use for displaying
  6. //results:
  7. var div = Y.Node.get('#weatherModule');
  8.  
  9. //Define a function to handle a successful response from
  10. //Yahoo! Weather. The success handler will find the response
  11. //object in its second argument:
  12. function successHandler(id, o){
  13. Y.log("Success handler called; handler will parse the retrieved XML and insert into DOM.", "info", "example");
  14. var root = o.responseXML.documentElement;
  15. var oTitle = root.getElementsByTagName('description')[0].firstChild.nodeValue;
  16. var oDateTime = root.getElementsByTagName('lastBuildDate')[0].firstChild.nodeValue;
  17. var descriptionNode = root.getElementsByTagName('description')[1].firstChild.nodeValue;
  18.  
  19. div.set("innerHTML", "<p>" + oTitle + "</p>" + "<p>" + oDateTime + "</p>" + descriptionNode);
  20.  
  21. Y.log("Success handler is complete.", "info", "example");
  22. }
  23.  
  24. //Provide a function that can help debug failed
  25. //requests:
  26. function failureHandler(id, o){
  27. Y.log("Failure handler called; http status: " + o.status, "info", "example");
  28. div.set("innerHTML", o.status + " " + o.statusText);
  29. }
  30.  
  31. //When the Get RSS button is clicked, this function will fire
  32. //and compose/dispatch the IO request:
  33. function getModule(){
  34. //Get the input value:
  35. var iZip = Y.Node.get('#zip').get("value");
  36.  
  37. //Create a querystring from the input value:
  38. var queryString = encodeURI('?p=' + iZip);
  39.  
  40. //The location of our server-side proxy:
  41. var entryPoint = '(assets/)weather.php';
  42.  
  43. //Compile the full URI for the request:
  44. var sUrl = entryPoint + queryString;
  45.  
  46. Y.log("Submitting request; zip code: " + iZip, "info", "example");
  47.  
  48. //Make the reqeust:
  49. var request = Y.io(sUrl, {
  50. method:"GET",
  51. on:
  52. {
  53. success:successHandler,
  54. failure:failureHandler
  55. }
  56. }
  57. );
  58. }
  59.  
  60. //Use the Event Utility to wire the Get RSS button
  61. //to the getModule function:
  62. Y.on("click", getModule, "#getWeather");
  63.  
  64. Y.log("When you retrieve weather RSS data, relevant steps in the process will be reported here in the logger/console.", "info", "example");
  65. }
  66. );
YUI({base:"../../build/", timeout: 10000}).use("io",
 
	function(Y) {
 
		//Get a Node reference to the div we'll use for displaying
		//results:
		var div = Y.Node.get('#weatherModule');
 
		//Define a function to handle a successful response from
		//Yahoo! Weather.  The success handler will find the response
		//object in its second argument:
		function successHandler(id, o){
			Y.log("Success handler called; handler will parse the retrieved XML and insert into DOM.", "info", "example");
			var root = o.responseXML.documentElement;
			var oTitle = root.getElementsByTagName('description')[0].firstChild.nodeValue;
			var oDateTime = root.getElementsByTagName('lastBuildDate')[0].firstChild.nodeValue;
			var descriptionNode = root.getElementsByTagName('description')[1].firstChild.nodeValue;
 
			div.set("innerHTML", "<p>" + oTitle + "</p>" + "<p>" + oDateTime + "</p>" + descriptionNode);
 
			Y.log("Success handler is complete.", "info", "example");
		}
 
		//Provide a function that can help debug failed
		//requests:
		function failureHandler(id, o){
			Y.log("Failure handler called; http status: " + o.status, "info", "example");
			div.set("innerHTML", o.status + " " + o.statusText);
		}
 
		//When the Get RSS button is clicked, this function will fire
		//and compose/dispatch the IO request:
		function getModule(){
			//Get the input value:
			var iZip = Y.Node.get('#zip').get("value");
 
			//Create a querystring from the input value:
			var queryString = encodeURI('?p=' + iZip);
 
			//The location of our server-side proxy:
			var entryPoint = '(assets/)weather.php';
 
			//Compile the full URI for the request:
			var sUrl = entryPoint + queryString;
 
			Y.log("Submitting request; zip code: " + iZip, "info", "example");
 
			//Make the reqeust:
			var request = Y.io(sUrl, {
				method:"GET",
				on:
					{
						success:successHandler,
						failure:failureHandler
					}
				}
			);
		}
 
		//Use the Event Utility to wire the Get RSS button
		//to the getModule function:
		Y.on("click", getModule, "#getWeather");
 
		Y.log("When you retrieve weather RSS data, relevant steps in the process will be reported here in the logger/console.", "info", "example");
	}
);

Proxy and Response

Once weather.php receives the querystring, it will construct and send an HTTP GET using CURL to retrieve the results from the Yahoo! Weather RSS feed. This allows the transaction to succeed while working around XMLHttpRequest's strict security policy.

  1. //Within a PHP block:
  2.  
  3. // Since the result is an XML document, the Content-type
  4. // header must be set to "text/xml" for the data to be
  5. // treated as XML and to populate responseXML.
  6. header("Content-Type:text/xml");
  7.  
  8. // io-weather_clean.html is the resource path of the Y! Weather RSS
  9. // with the appended querystring of zip code/location id.
  10. $url = 'http://xml.weather.yahoo.com/forecastrss?'.getenv('QUERY_STRING');
  11.  
  12. // This function initializes CURL, sets the necessary CURL
  13. // options, executes the request and returns the results.
  14. function getResource(io-weather_clean.html){
  15. $ch = curl_init();
  16. curl_setopt($ch, CURLOPT_URL, $url);
  17. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  18. $result = curl_exec($ch);
  19. curl_close($ch);
  20.  
  21. return $result;
  22. }
  23.  
  24. // Call getResource to make the request.
  25. $feed = getResource($url);
  26.  
  27. // Return the results.
  28. echo $feed;
//Within a PHP block:
 
// Since the result is an XML document, the Content-type
// header must be set to "text/xml" for the data to be
// treated as XML and to populate responseXML.
header("Content-Type:text/xml");
 
// io-weather_clean.html is the resource path of the Y! Weather RSS
// with the appended querystring of zip code/location id.
$url = 'http://xml.weather.yahoo.com/forecastrss?'.getenv('QUERY_STRING');
 
// This function initializes CURL, sets the necessary CURL
// options, executes the request and returns the results.
function getResource(io-weather_clean.html){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch);
 
        return $result;
}
 
// Call getResource to make the request.
$feed = getResource($url);
 
// Return the results.
echo $feed;

Copyright © 2009 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings