0

This is some code I wrote to get local weather:

var temp;

function displayWeather(latitude, longitude) {
  var request = new XMLHttpRequest();
  // console.log(latitude);
  var method = 'GET';
  var url = 'https://fcc-weather-api.glitch.me/api/current?lon=' + longitude + '&lat=' + latitude;
  var async = true;
  request.open(method, url, async);
  request.onreadystatechange = function() {
    if (request.readyState == 4 && request.status == 200) {
      var data = JSON.parse(request.responseText);
      // alert(request.responseText); // check under which type your city is stored, later comment this line
      var skyConditions = data.weather[0].description;
      $("#sky").html(skyConditions);
      temp = data.main.temp;
      $("#temp").html("<span id='tempNum'>" + Math.floor(temp) + "</span>" + "C");
      var icon = data.weather[0].icon;
      $("#icon").html("<img src=" + icon + ">");
      // alert(data.weather[0].main);
      if (data.weather[0].main == "Clouds") {
        $("body").addClass("cloudy");
      } else if (data.weather[0].main == "Rain") {
        $("body").addClass("rainy");
      } else if (data.weather[0].main == "Clear") {
        $("body").addClass("sunny");
      } else if (data.weather[0].main == "Thunderstorm") {
        $("body").addClass("thunder");
      }
    }
  };
  request.send();
};

The problem I'm having is that the value assigned for 'temp' gets lost once it's out of the function. So if I call 'temp' somewhere else in the code, I get undefined rather than the value I assigned in 'weatherDisplay'. I can't seem to get a way around it annoyingly;

Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
  • That's because AJAX stands for **Asynchronous** JavaScript And XML – adeneo Aug 09 '17 at 20:11
  • Also, if you are already using JQuery. You should use [`$.ajax`](http://api.jquery.com/jquery.ajax/) it's more convenient than using `XMLHttpRequest` directly – litelite Aug 09 '17 at 20:13
  • temp is set in the function for sure, I just want to know if there is a way so that the value doesn't disappear once it's out of the function – nijat A Aug 09 '17 at 20:15
  • @nijatA It's not that the value "disappears" once you've left the function. It's that you're trying to access it before it's been assigned. Read the question that adeneo marked as a duplicate. It will explain the whole issue to you. – Mike Cluck Aug 09 '17 at 20:17

0 Answers0