I'm facing an issue while creating a basic HTML page that fetches data from the OpenWeather API using AJAX. The problem lies in my latitude and longitude parameters not being correctly inserted into the URL. I've been trying to identify the mistake, but haven't had any luck so far.
My JavaScript Code:
var request = new XMLHttpRequest();
function getWeather() {
var latitude = document.getElementById("lat").value;
var longitude = document.getElementById("long").value;
request.open('GET', 'https://openweathermap.org/data/2.5/weather?lat=' + latitude + '&lon=' + longitude + '&appid=547fa6dfa44cff13fa92bba2c465b366', true);
request.send();
request.onreadystatechange = displayData;
}
function displayData() {
if(request.readyState === 4 && request.status === 200) {
var resultData = JSON.parse(request.responseText);
var temperature = document.getElementById("temperature");
var windspeed = document.getElementById("windspeed");
temperature.value = resultData.main.temp;
windspeed.value = resultData.wind.speed;
document.getElementById("resultset").style.visibility = "visible";
}
}
window.onload = function() {
var btn = document.getElementById("btn");
btn.addEventListener("click", getWeather, false);
}
My HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta id="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/styles.css" />
</head>
<body>
<header>
<h1>Weather Report</h1>
</header>
<article>
<h2>Weather Data</h2>
<form action="#" method="post" id="theForm" novalidate>
<fieldset id="zipset">
<label for="lat" id="lat">Latitude:</label>
<input id="lat" type="number" />
<label for="long" id="long">Longitude</label>
<input id="long" type="number" />
</fieldset>
<fieldset id="resultset">
<label for="temperature" id="temperature">Temperature:</label>
<input id="temperature" type="text" />
<label for="windspeed" id="windspeed">Wind Speed:</label>
<input id="windspeed" type="text" />
</fieldset>
</form>
<button id="btn">Submit Coordinates</button>
</article>
<script src="js/weather_report1.js"></script>
</body>