In the following code I make two FETCHs to a URL. The first one returns a URL and the second one tries to do a FETCH on that URL. In the first FETCH I store the URL retiurned to a what I think is a global variable “observationsURL”. However when the code executes the second FETCH it says that the variable is not defined and errors off. I have tried putting the VAR declaration at the very top of the code but that also produces errors. What am I missing? I understand it is a scope problem but not sure how to proceed. Thanks!
var ObservationDataURL = "";
$(document).ready(function() {
$("#searchInput").on("keyup", function(e) {
var cityname = e.target.value;
const APIKey = "...";
var firstURL = "https://api.weather.gov/points/44.631,-86.0725";
// Make a request to the server
$.ajax({
url:firstURL,
}).done(function(weatherdata) {
console.log(weatherdata.properties.relativeLocation.properties.city);
var cityName = weatherdata.properties.relativeLocation.properties.city
ObservationDataURL = weatherdata.properties.forecastGridData;
console.log(ObservationDataURL);
var targetdataURL = ObservationDataURL + "/object/properties/temperature/values/value";
console.log("Target data URL is:");
console.log(targetdataURL);
});
});
})
let addr3 = 'https://api.weather.gov/points/44.630978,-86.072480';
fetch(addr3)
.then(data => data.json())
.then(json => {
console.log(json);
// do stuff with json data here
var forecastURL = addr3;
var observationsURL = "";
observationsURL = json.properties.observationStations;
console.log(forecastURL);
console.log(observationsURL);
})
.catch(console.log);
fetch(observationsURL)
.then(data => data.json())
.then(json => {
console.log("New stuff");
console.log(json);
})
.catch(console.log);