0

I have a feature on my site where the background changes based on the weather. I can successfully change the background if I declare a static zip code, but I want to be able to automatically fetch the zip code from the user's IP credentials.

I tried incorporating a script to fetch the zip code, which works well, but I can't figure out how to get the zip code into the weather function. I've tried declaring a global variable, but for some reason it doesn't work. I get the error in the console:

Uncaught TypeError: Cannot read property 'text' of undefined.

Any thoughts on where I went wrong? Thanks!

CODE

var zipcode;
$.getJSON("http://api.ipinfodb.com/v3/ip-city/?key=my_api_key&format=json&callback=?",
function(data){
    zipcode = data['zipCode']; //DE,AT ...
});

$(document).ready(function() {  
  $.YQL = function(query, callback) {
      $.getJSON('http://query.yahooapis.com/v1/public/yql?callback=?', { q: query, format: 'json' }, callback);
  };
  $.YQL("select * from rss where url='http://weather.yahooapis.com/forecastrss?p=" + zipcode + "'", function (data) {
     var w = data.query.results.item,
         klass = w.condition.text,
         current
         encodedclass = klass.replace(/\s+/g, '-').toLowerCase();

     $('body').addClass(encodedclass);
  });
});
Dryden Long
  • 10,072
  • 2
  • 35
  • 47
  • 1
    Your problem is that the call to get the zipcode is asynchronous. Make the call to get the weather from your callback or else use `.then` to chain your call to get the weather onto the end of the call to get the zipcode. – Matt Burland Feb 18 '14 at 19:27
  • 1
    Is current supposed to be on a line by itself with no assignment or comma? – Skrivener Feb 18 '14 at 19:27
  • @Skrivener Funny, I never noticed that. I thought it was a typo within my post at first, but my actual code is the same way and functions correctly... – Dryden Long Feb 18 '14 at 19:35
  • `w.condition` is evaluating to `undefined` – Vikram Feb 18 '14 at 19:49

1 Answers1

0

Try this:

var getZip = $.getJSON("http://api.ipinfodb.com/v3/ip-city/?key=my_api_key&format=json&callback=?", function(data){
    zipcode = data['zipCode']; //DE,AT ...
});

And then in your doc ready:

getZip.then(function() { 
    $.YQL("select * from rss where url='http://weather.yahooapis.com/forecastrss?p=" + zipcode + "'", function (data) {
        var w = data.query.results.item,
        klass = w.condition.text,
        current,    // did you miss a comma here?
        encodedclass = klass.replace(/\s+/g, '-').toLowerCase();
        $('body').addClass(encodedclass);
    })
});

And here's the docs on using .then

Matt Burland
  • 44,552
  • 18
  • 99
  • 171