javascriptajaxopenweathermap

building a 5 day forecast using open weather api AJAX and JS


I am trying to build a 5-day forecast using open weather API. The parameters I'm using based on the website are not working, it returns undefined. Also, is there a way I can get the main temp from day 1, 2 and etc. Please help

here's my code:

$.ajax({
  url: 'http://api.openweathermap.org/data/2.5/forecast', //API Call
  dataType: 'json',
  type: 'GET',
  data: {
    q: city,
    appid: key,
    units: 'metric',
    cnt: '10'
  },
  success: function(data) {
    var wf = '';
    $.each(data, function(index, val) {
      wf += '<p><b>' + data.city.name + '</b><img src=http://openweathermap.org/img/w/' + data.list[0].weather.icon + '.png></p>' + data.list[0].main.temp + '&deg;C' + ' | ' + data.list[0].weather.main + ", " + data.list[0].weather.description
    });
    $("#showWeatherForcast").html(wf);
  }
});

Solution

  • Your current code is not too far off. I suggest that you use console.log(data) in your success function to see what pops out while you are testing. It will help you understand the returned data structure.

    If you take a look in your browser console now, you will likely see some warnings. I recommend you use https instead of http URLs for both your main API call and your image URLs to avoid some of them, including Mixed Content warnings.

    The below code is adapted from yours and displays a temperature, a description, and an icon per each val in data.list in city. Note that $.each here loops through properties of each val (0-9) in the array data.list to access the data you need. Your current code tries to access a val of data.list[0][some property] each time, returning undefined.

    var key = "YOUR KEY";
    var city = "YOUR CITY"; // My test case was "London"
    var url = "https://api.openweathermap.org/data/2.5/forecast";
    
    $.ajax({
      url: url, //API Call
      dataType: "json",
      type: "GET",
      data: {
        q: city,
        appid: key,
        units: "metric",
        cnt: "10"
      },
      success: function(data) {
        console.log('Received data:', data) // For testing
        var wf = "";
        wf += "<h2>" + data.city.name + "</h2>"; // City (displays once)
        $.each(data.list, function(index, val) {
          wf += "<p>" // Opening paragraph tag
          wf += "<b>Day " + index + "</b>: " // Day
          wf += val.main.temp + "&degC" // Temperature
          wf += "<span> | " + val.weather[0].description + "</span>"; // Description
          wf += "<img src='https://openweathermap.org/img/w/" + val.weather[0].icon + ".png'>" // Icon
          wf += "</p>" // Closing paragraph tag
        });
        $("#showWeatherForcast").html(wf);
      }
    });