views:

1412

answers:

4

I'm working on a Drupal 6 module where I use jquery (and more specifically, the $.ajax method) to retrieve a RSS feed from Yahoo's weather API. I decided against using the JFeed library because I need access to the elements with "yweather" prefix (and I couldn't find a way of accessing them via JFeed). I decided to use the $.ajax method and parse the XML response instead. The JavaScript code below works fine in Firefox and IE but does not work in Safari (or Chrome FWIW):

function parseXml(xml) {
  var atmosphere = xml.getElementsByTagName("yweather:atmosphere");

  var humidity = atmosphere[0].getAttribute("humidity");

  $('#weatherFeed').html("Humidity: " + humidity);
  $('#weatherFeed').append(
     "<div style=\"text-align: center;margin-left: auto; margin-right: auto;\">" + 
     city + ", " + state + "</div>");
}

function getData(){
   $.ajax({
      type:   'GET',
      url:    'proxy.php?url=http://weather.yahooapis.com/forecastrss&amp;p=94041',
      dataType: 'xml',
      success:  function(xml) {
      parseXml(xml);
 }
 }); 
}

if(Drupal.jsEnabled) {
$(function() {
      getData();
      setInterval("getData()", 30000);
      });   
}

When I check the error console in Safari I see the following error message: TypeError: Result of expression 'atmosphere[0]' [undefined] is not an object. Is there an issue with using getElementsByTagName in Safari? Should I be accessing the object that's returned by getElementsByTagName differently?

A: 

Have you tried atmosphere[1] instead of 0 for Chrome and Safari?

ZippyV
Yes I just tried that and got the same error message in Safari as I was before (TypeError: Result of express 'atmosphere[1]' [undefined] is not an object.
toddk
+1  A: 

Maybe just treating the the XML as data and using jQuery selectors to pull out what you want would work.

$(xml).find("yweather:atmosphere").attr("humidity") - you might need to use filter instead of find - what do you think?

Andy Gaskell
This code got the error to disappear in Safari but did not give me a valid value back yet (still "undefined"). I tested this out in Firefox and everything seems to be working there...
toddk
A: 

link text

A: 

I had the exact same problem, but came across the answer here: http://reference.sitepoint.com/javascript/Document/getElementsByTagName

It has to do with the yweather namespace. Use getElementByTagNameNS function instead.

var atmosphere = xml.getElementsByTagName("yweather:atmosphere");

becomes

var atmosphere = xml.getElementsByTagNameNS("http://xml.weather.yahoo.com/ns/rss/1.0","atmosphere");

function reference: http://reference.sitepoint.com/javascript/Document/getElementsByTagNameNS

PetroleumJelliffe