Search code examples
jqueryjsongetjson

jquery output looping and can't get getjson values out


I have the following code:

    var weatherstations = 
       [{"Name":"city1","Code":"CODE1"},
        {"Name":"city2","Code":"CODE2"},
        {"Name":"city3","Code":"CODE3"},
        {"Name":"city4","Code":"CODE4"},
        {"Name":"city5","Code":"CODE5"}];


      $.each(weatherstations, function(key,value) {
        //console.log(value.Name); // shows the city in the console log

         $.getJSON('http://www.domain.com/getweather-json.php?weatherstation=' + value.Code, function(result){
            $.each(result, function(index, item){
          console.log(item.clouds); // shows cloud variable in console log


    //        $('#wx').append('<h2>'+item.temp+'</h2><ul><li>'+value.Name+'</li><li>'+item.clouds+'</li><li>'+item.wind+'</li></ul>');
            }); //.each json call
         }); //.getjson
      }); //.each weatherstations

The problems I'm running into is.. that I do not get 5 lines (IF I have that $(wx) line uncommented), but 20: Four for each city. On top of that.. the console.log(item) gives me ALL the data back from the json. If I do console.log(item.clouds), then I get "undefined" back.. Why is this?

JSON example: {"clouds":"mostly cloudy","conditions":"","temp":"12°F","wind":"varies 2 mph"}

(when I view the json in that url, I see a few empty lines and then the json.. not sure if that causes the 4x city that shows up)


Solution

  • Not sure why the .each wouldn't work.. and why it would return 4 lines each time.

    I changed the getJSON code to:

    $.getJSON('http://www.domain.com/getweather-json.php?weatherstation=' + value.Code, function(result){
    
            $('#wx').append('<h2>'+result.temp+'</h2><ul><li>'+value.Name+'</li><li>'+result.clouds+'</li><li>'+result.wind+'</li></ul>');
    }); //.getjson
    

    And now it gives me the feedback I needed.