Search code examples
javascriptjqueryajaxopenweathermap

retrieving data from API using JQuery/Ajax


enter image description here

I am trying to get the information from openweathermap api into my app. I tried using ajax to get the data, but it is shown as undefined.

   $(function(){

        var $temp = $('#temperature');
        var $humidity = $('#humidity')
        temp = document.getElementById("temperature");
        $.ajax({
            type: 'GET',
            url: 'http://api.openweathermap.org/data/2.5/weather?q={' +
                  markers["title"] + '}&APPID=' + APPID,
            success: function(data){
              console.log('success', data);
              $temp.append(data.main.temp);
              $humidity.append(data.main.humidity);
            }

        });

      });

  var contentString = '<div id="content">'+
      '<div id="siteNotice">'+
      '</div>'+
      '<h1 id="firstHeading" class="firstHeading">' + markers["title"] + '</h1>'+
      '<div id="bodyContent">'+
      '<div class = "temperature"><span id = "temperature"> '+ temp +' </span>&degC</div>' +
      '<div class = "humidity">'+ humidity +'<span id = "humidity"></span>%' +
      '</div>';`

Solution

  • You need to JSON.parse() your data. $ajax is likely returning a string, so you need to parse the data before you can get properties out of it.

    The reason you are getting an undefined error is because you can't retrieve properties of a string.