Search code examples
javascriptxmljsonwunderground

Json request comes back 'UNDEFINED' using Wunderground API


I have set up a function and a callback to retrieve some data regarding weather alerts. For some reason the data comes back as 'UNDEFINED'. I'm fetching the data through json although I would prefer to... fetch XML and callback json, however fetch and return json is fine.

Below is my code, but I have put it into a jsfiddle to make it easier to read.

http://jsfiddle.net/seversides/G7Wr8/

Javascript

$(function () { 
// Specify the location and Api key 
var apiKey = 'myapikey';
var location = 'zmw:00000.1.16172';

// Run the query (pull data from feed)
var url = 'http://api.wunderground.com/api/' + apiKey + '/alerts/q/' + location +     '.json';

window['wCallback_3'] = function(data) {
// Get any weather alerts
var info = data.alerts; 
// Warning level and color
$('#wWarning .wLevel').append('<TD>' + info.wtype_meteoalarm + '</TD>');
$('#wWarning .wColor').append('<TD>' + info.level_meteoalarm_name + '</TD>');

};

// Callback
$.ajax({
url: url,
dataType: 'jsonp',
contentType: "application/json",
cache: true, 
jsonpCallback: 'wCallback_3'
});

});

HTML

<div id="wWarning">

<table class="wBox">  
<h1 class="wLevel"></h1>
<h1 class="wColor"></h1>  
</table>

</div>

When I run the code it displays the data as UNDEFINED. Why isn't it retuning the right data?


Solution

  • The "UNDEFINED" is referring to the callback function, because it doesn't exist as part of the request.

    You're telling it that you want the output to be in JSONP in the line:

    dataType: 'jsonp',
    

    But that API is responding with JSON (excluding a callback).

    In order to access it cross domain with JSONP (which is the right protocol for what you're looking for), you need to use the AutoComplete API:

    http://www.wunderground.com/weather/api/d/docs?d=autocomplete-api&MR=1

    Then, you set the callback with cb=myCallback in the GET string:

    http://autocomplete.wunderground.com/aq?format=JSON&query=Anchorage&cb=myCallback

    The problem is, I don't see any way in that API to use the zmw= values, so you may need a workaround for the area of interest.