0

I want to be able to call the variables I pull from a JSON string in my actual HTML code so in the head of my code I have the following.

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    <script>
    $.getJSON('http://api.openweathermap.org/data/2.5/weather?zip=34285,us&units=imperial', function(data) {
        temp = data.main.temp;
        weather = data.weather[0].description;
    });
    </script>

And In the body of my code I have the following

<script>
document.write(temp)
document.write(weath)
</script>

For some reason the variables will not show up. If I try to put the entire function in my body and add the code it works but it rewrites my entire page. How can I get it so that I can reference just the variables and add them to my HTML code.

  • Not sure if this a duplicate of http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call or http://stackoverflow.com/questions/4537963/what-are-alternatives-to-document-write; probably both. – JJJ Apr 21 '15 at 15:46
  • The getJSON is async. Thus you `document.write` are executed before the JSON is actually get. Try a `console.log()` above the `document.write` and one in the success of the getJSON. That should rule that option out – David Laberge Apr 21 '15 at 15:47
  • They aren't writing anything because they are being executed before you have received the response from the weather API. Put both writes inside the callback function, where you set both variables. – Matt Apr 21 '15 at 15:48

0 Answers0