1

I have a form where user types in the city name, I want to make an API call and get weather results in that city and then display it in the console.

I'm getting an error because for some reason the variable that holds input.value is not being concatenated into the string.

Here's the code:

var request;
var input1 = document.getElementById('city');
var api = 'https://api.openweathermap.org/data/2.5/weather?q=';
var apikey = '&APPID=433b12b793d7ebc17989745c069a540b';
var sum = api + input1.value + apikey;

function myFunction() {

  request = new XMLHttpRequest();

  request.open('GET', sum, true);
  request.onload = function() {

    var data = JSON.parse(this.response);
    if (request.status >= 200 && request.status < 400) {
      console.log(data);
    } else {
      console.log(input1.value);
    }
  }

  request.send();
}
myFunction(input1.value);
<input id='city' value='San Francisco'>

Thanks for any help!

2
  • Those variable initializations should be inside the function. As it is, they'll just run once when the page first loads. Commented Sep 2, 2018 at 13:23
  • 1
    If you log input1.value the correct value shows up ? Commented Sep 2, 2018 at 13:23

1 Answer 1

1

Your code is ok, you just need to put everything inside the function.

 <script>
    function myFunction() {

        var request;
        var input1 = document.getElementById('city');
        var api = 'https://api.openweathermap.org/data/2.5/weather?q=';
        var apikey =
            '&APPID=433b12b793d7ebc17989745c069a540b';
        var sum = api + input1.value + apikey;

        request = new XMLHttpRequest();

        request.open('GET', sum, true);
        request.onload = function () {

            var data = JSON.parse(this.response);
            if (request.status >= 200 && request.status < 400) {
                console.log(data);
            } else {
                console.log(input1.value);
            }
        }

        request.send();
    }
</script>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.