Unable to submit form data to create object from URL in weather app

Unable to submit form data to create object from URL in weather app
0.0 0

#1

I have successfully built a weather app which retrieves weather conditions based on geolocation. I modified the code to retrieve weather using the city name which is passed as a variable from a javascript alert box which works fine:

var city = window.prompt("Enter Your City");
       updateByCity(city);

However when I create a form on the app itself and try to pass the form data to the updateByCity function using the following code:

document.getElementById("submit").onclick = function() {
		 var city = document.getElementById("city").value;
		 
		 updateByCity(city);

The application does not retrieve any weather data. I dont know why. Using alerts I discovered that it passes the city variable to the updateByCity(city) function and successfully creates a URL to pass to AJAX but for some reason the logic breaks down when parsing the AJAX response.

Here is the code where I think I am having issues:

function updateByCity(city) {
	//alert(city);
    var url = "http://api.openweathermap.org/data/2.5/weather?" + "q=" + city + "&APPID=" + APPID;
	sendRequest(url);
	
}

function sendRequest(url) {
	
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
	    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			var data = JSON.parse(xmlhttp.responseText);
			var weather = {};
			weather.icon = 'https://cors.5apps.com/?uri=http://openweathermap.org/img/w/' + data.weather[0].icon + '.png';
            weather.humidity = data.main.humidity;
            weather.wind = data.wind.speed;
			//weather.direction = data.wind.deg;
            weather.direction = degreesToDirection(data.wind.deg);
			weather.desc = data.weather[0].description;
            weather.loc = data.name;
           // weather.temp = data.main.temp;
            weather.temp = K2F(data.main.temp);
            update(weather);
        } 
    };
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

It works fine if I send the variable via the alert but not via clicking Submit button on the form for some reason.


#2

We need to see your HTML code also. Do you have a link to your code?


#3

I have just created a CodePen.

I have noticed that passing the city variable via the alert box also does not work in CodePen but works in Brackets on the localhost.


#4

I have also noticed that if I set the xmlhttp request to synchronous

 xmlhttp.open("GET", url, false);

The weather flashed momentarily on the app.


#5

I finally figured out what the problem was. The page was refreshing itself and wiping all of the data returned by the API. This is due to the form behavior.

As soon as I removed the form tags everything started working. It took me hours of research and testing to realize this.