Stuck in local weather app project

Stuck in local weather app project
0

#1

here is my JS code and err info. the location name can be show. but the result can not show weather information. I do not know how to solve it. please help me. :sleepy::tired_face:

$(document).ready(function () {
var lat;
var lon;

$('#location').text('loading . . .');
function getLocation() {
  $.ajax({
    url: 'https://ipapi.co/jsonp',
    method: 'GET',
    dataType: 'jsonp',
    jsonpCallback: 'callback',
    success: function (response) {
      $('#location').text(response.city + ',' + response.country);
      lat = response.latitude;
      lon = response.longitude;
    },
  });
}
getLocation();
function getWeather(lat, lon) {
  $.ajax({
        url: 'https://fcc-weather-api.glitch.me/api/current?lat=' + lat + '&lon=' + lon,
        method: 'GET',
        dataType: 'JSON',

        success: function (data) {
            $('#location').text(data.weather[0].main);

          },
      });
}
getWeather(lat, lon);

});


#2

Hi @metrical1

This is a classic issue that newer JS developers will run into due the asynchronous nature of ajax requests.

I definitely recommend researching JS and ajax asynchronous behavior, I just googled but this article might be a good start: https://medium.com/front-end-hacking/ajax-async-callback-promise-e98f8074ebd7.

Essentially, the data from getLocation() won’t have been processed before the call to getWeather(), so when getWeather tries to access the lat and lon values, they will be undefined.

Try calling getWeather from within the success function of the getLocation ajax call and passing the lat/lon you get from the response.


#3

Hello @joesmith100

Thank you! Now I got the correct result. I appreciate you!:rofl: