I'm playing around with using the forecast.io API to (eventually) make something that will email me every day about the weather in my area. When I make a request to the API, it gives me a JSON object with all the information in it. I'm using JavaScript and PHP write this. Here is the code I have so far (it's a bit messy right now):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
var latitude = "42";
var longitude = "-71";
var coordinates = latitude + "," + longitude;
var forecast;
$.ajax({
url: "<?php echo $_SESSION['url'] ?>42,-71",
type: "GET",
dataType: "jsonp",
crossDomain: true,
jasonpCallback: 'blah',
success: function(data) {
forecast = data;
console.log(forecast.daily.summary);
},
error: function() {
console.log("This failed.");
}
});
//**********************************
document.write(getDailySummary());
//**********************************
function getDailySummary() {
var summary = forecast.daily.summary;
return "<p>" + summary + "</p>";
}
</script>
Right now, the $.ajax() statement runs successfully, and the forecast summary is logged in the console. However, the getDailySummary()
doesn't run so well. I get the following error when I run this:
Uncaught TypeError: Cannot read property 'daily' of undefined index.php:42
getDailySummary index.php:42
(anonymous function) index.php:37
Rain on Thursday and Friday; temperatures rising to 85° on Saturday. index.php:28
This makes it sound like forecast
is undefined. My initial thought is that it has to do with scope, but I've tried fiddling around with all sorts of things, including defining forecast as window.forecast
, but I always get this error. Where am I going wrong?