YUI Library Examples: Connection Manager: Retrieving a Yahoo! Weather RSS Feed

Connection Manager: Retrieving a Yahoo! Weather RSS Feed

This example demonstrates how to use the Connection Manager 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, your desired units (C or F), and click "Get Weather RSS".

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.

Enter *F* for Fahrenheit or *C* for Celsius temperature unit.

Exploring the Code for This Example

Load the Yahoo Global Object and Connection Manager source files:

1<script src="yahoo.js"
2<script src="connection.js"
view plain | print | ?

Callback Object and the Weather RSS

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

1// This is the response display container 
2var div = document.getElementById('weatherModule'); 
3// This is a reference to the HTML form. 
4var oForm = document.getElementById('wForm'); 
5 
6/*
7 * This method will traverse the response XML document and build a
8 * simple HTML module comprised of data from the following tags:
9 *
10 * Data in the first <title> tag in the document.
11 * Data in the first <lastBuildDate> tag in the document.
12 * HTML from the second <description> tag in the document.
13 *
14 */ 
15function successHandler(o){ 
16    var root = o.responseXML.documentElement; 
17    var oTitle = root.getElementsByTagName('description')[0].firstChild.nodeValue; 
18    var oDateTime = root.getElementsByTagName('lastBuildDate')[0].firstChild.nodeValue; 
19    var descriptionNode = root.getElementsByTagName('description')[1].firstChild.nodeValue; 
20 
21    // Format and display results in the response container. 
22    div.innerHTML = "<p>" + oTitle + "</p>" + "<p>" + oDateTime + "</p>" + descriptionNode; 
23
24 
25/*
26 *
27 * This is a simple failure handler that will display
28 * the HTTP status code and status message if the resource
29 * returns a non-2xx code.
30 *
31 */ 
32function failureHandler(o){ 
33    div.innerHTML = o.status + " " + o.statusText; 
34
view plain | print | ?

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 name-value pairs. In this example, we will use the following parameters:

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

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 temperature and creates a querystring:

1function getModule(){ 
2 
3    // retrieve the field values for the zip code 
4    // input and the unit input. 
5    var sLocation = oForm.elements['zip'].value; 
6    var sUnit = oForm.elements['unit'].value; 
7 
8    // entryPoint is the base URL 
9    var entryPoint = 'php/weather.php'
10 
11    // queryString is the key-value pairs of zip and unit. 
12    var queryString = encodeURI('?p=' + sLocation + '&' + 'u=' + sUnit); 
13    var sUrl = entryPoint + queryString; 
14 
15    // Initiate the HTTP GET request. 
16    var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, { success:successHandler, failure:failureHandler }); 
17
view plain | print | ?

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. 
6header("Content-Type:text/xml"); 
7 
8// $url is the resource path of the Y! Weather RSS 
9// with the appended querystring of zip code/location id and 
10// temperature unit. 
11$url = 'http://xml.weather.yahoo.com/forecastrss?'.getenv('QUERY_STRING'); 
12 
13// This function initializes CURL, sets the necessary CURL 
14// options, executes the request and returns the results. 
15function getResource($url){ 
16        $ch = curl_init(); 
17        curl_setopt($ch, CURLOPT_URL, $url); 
18        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
19        $result = curl_exec($ch); 
20        curl_close($ch); 
21 
22        return $result
23
24 
25// Call getResource to make the request. 
26$feed = getResource($url); 
27 
28// Return the results. 
29echo $feed
view plain | print | ?

YUI Logger Output:

Logger Console

INFO 63ms (+63) 11:22:45 AM:

example:

When you retrieve weather RSS data, relevant steps in the process will be reported here in the logger.

INFO 0ms (+0) 11:22:45 AM:

global:

Logger initialized

Note: You are viewing this example in debug mode with logging enabled. This can significantly slow performance.

Reload with logging
and debugging disabled.

More Connection Manager Resources:

Copyright © 2007 Yahoo! Inc. All rights reserved.

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