Reputation: 435
Thanks to help on an earlier question, i am able to Retrieve a JSON and access information from it.
FINAL WORKING CODE FOR FUTURE REFERENCE
<script>
var co2;
var url="/solarpv/api/co2/list"
var jsonObject;
$(document).ready(function(){
$.getJSON(url,function(result){
var jsonObject = result;
alert(result[0].Cumulative_CO2);
co2 = result[0].Cumulative_CO2;
alert(co2);
$('#ajaxRequest').html("An average person uses " + co2 + " pounds of c02");
});
});
</script>
<h3> Some CO2 Comparisons </h3>
<p style="width:600px;"> </p>
<ul>
<li>An average person produces 1.98 pounds a day of CO2. </li>
<li> Plants absorb .0040786 lbs per meter squared per day. </li>
<li> An average tree absorbs 48.061 pounds of CO2 per year. </li>
<li id="ajaxRequest">
<script>
document.write("An average person uses " + co2 + " pounds of c02");
</script>
</li>
</ul>
However, When I store the results in a var
called co2
and then use that in my html like this
it prints undefined
for the co2 variable on my page.
both alerts alert(result.Cumulative_CO2);
and alert(co2);
print the same thing, so for some reason co2 is not keeping its value when it leaves the function. any pointers would be greatly appreciated.
UPDATE
This is what the URL called returns [{"Cumulative_CO2":"406465.968076","Year":"2013","Month":"3","Day":"30"}]
Upvotes: 0
Views: 86
Reputation: 434
When the $.getJSON is done loading just inject your variable into the paragraph. That way once the object is stored and co2 is created jQuery will change the sentence to the proper content you want and the variable will be inserted. Here's an example.
<script>
var co2;
$(document).ready(function(){
$.getJSON(url,function(result){
var jsonObject = result;
alert(result.Cumulative_CO2);
co2 = result.Cumulative_CO2;
$('p').html('random co2 fact here ' + co2 + ' pounds of c02');
});
});
</script>
Upvotes: 3
Reputation: 943579
The function you pass to ready()
won't run until after the DOM has been constructed.
getJSON
will send an HTTP request and then finish (allowing execution to continue). The function you pass to getJSON()
won't run until an HTTP response has been received.
You won't be able to use the response data until both those events have occurred. Until then it will be undefined
.
Move your logic for using the data so it is inside the function you pass to getJSON
. That is the point of having a callback function there.
Upvotes: 3