0

I know this should be easy but I have spent hours trying to get this to work.

I am getting back JSON data from a weather api based on zip code. I want the zip code to come from and input(see below). However, when I use document.getElementById('city').value; I keep getting an error message in the console. What am I doing wrong? I know where the problem area is but i'm not sure how to fix it?

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Weather API</title>
    <!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->
    <script src="main.js"></script>
</head>
<style>
    li { list-style-type: none; }
    .buffer { padding: 0.5rem 0; }
</style>
<body>
    <p>My API call for weather</p>
    <div class="buffer"> 
        <input name="city" type="text" id="city" />
        <button id="submit" onclick="weatherHistory();">Submit</button>
    </div>

    <div id='blank'> </div>

</body>
</html>

JS

const api = 'http://api.openweathermap.org/data/2.5/weather?';
const city = document.getElementById('city').value; // PROBLEM HERE 
const input = 'zip=' + city + ',us';
const api_key = '&APPID= my-key-here';
const units = '&units=imperial';
var url = api + input + api_key + units; 


function get(url) {
    return new Promise((resolve, reject) => {
        const req = new XMLHttpRequest();
        req.open('GET', url);
        req.onload = () => req.status === 200 ? resolve(req.response) : reject(Error(req.statusText));
        req.onerror = (e) => reject(Error(`Network Error: ${e}`));
        req.send();
    });
}


function weatherHistory() {    
    get(url)
        .then((data) => {
            const x = JSON.parse(data);
            const max = x.main.temp_max;
            const min = x.main.temp_min;
            const humidity = x.main.humidity;
            var div = document.getElementById('blank');
            const api_data = "<li> Min Temp: " + min + "</li>" + "<li> Max Temp: " + max + "</li>" + "<li>Humidity: " + humidity + "</li>"  
            div.innerHTML = api_data;
        })
        .catch((err) => {
            console.log('Oops something went wrong, please try again');
        });
}

img

lcdcoder
  • 3
  • 5
  • get and process the value when event occurs – charlietfl Dec 14 '17 at 20:05
  • 1
    Your ` – CRice Dec 14 '17 at 20:06
  • Wrap your code into: `window.onload = function(){ /* Code goes here... */ };`. – Danny Fardy Jhonston Bermúdez Dec 14 '17 at 20:08
  • CRice is right, because you are running your script before your html elements are created you are looking for something which doesn't exist yet with the problem line, `const city = document.getElementById('city').value;` Moving the script to before you close the html should work, ignoring other problems. – SHolmes Dec 14 '17 at 20:10
  • Oh my gosh....simply a script tag out of line....Well, thank you all. I knew it had to be something trivial. Works great now though. – lcdcoder Dec 15 '17 at 00:56
  • All comments are outdated, you can do `` just add [defer](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-defer) that is option 4 of [this](https://stackoverflow.com/a/8716680/1641941) aswer – HMR Dec 15 '17 at 07:42

0 Answers0