skip to Main Content

When I put this into the browser, it brings back the json object just fine to me with all the weather data:
http://api.openweathermap.org/data/2.5/weather?zip=90210&units=imperial&appid={API Key}

However, I’m using my XAMPP Apache in the htdocs folder to try and test it out in my code. Can someone please look at my code and see what in the what is wrong here? Thank you so much for the help.

var weatherInfo = document.getElementById("weather");
var zipCodeForm = document.getElementById("zipCodeForm");

function getWeather(zipCode){
	//create the url for the request
	var endpoint = "http://api.openweathermap.org/data/2.5/weather";
	var apiKey = {API Key};
	var queryString = "zip=" + zipCode + "&units=imperial&appid=" + apiKey;
	var url = endpoint + "?" +queryString;

	//create the request to get the weather data
	var xhr = new XMLHttpRequest();
	xhr.addEventListener("load", responseReceivedHandler);
	xhr.requestType = "json";
	xhr.open("GET", url);
	xhr.send();

	console.log("getWeather")
	console.log(xhr.response.status);
}

function responseReceivedHandler(){
	if(this.status === 200){
		weatherInfo.innerHTML = "Current temperature: " + this.response.main.temp;
	}

	else{
		weatherInfo.innerHTML="Not working";
	}

	console.log("responseReceivedHandler")


}

getWeather(90210);
 <body>
 	<form id="zipCodeForm">
 		<label for="zipCode">Please enter your zip code: </label>
 		<input type="text" name="zipCode" id="zipCode">
 		<input type="submit" name="submit">
 	</form>

 	<div id="weather"></div>
 </body>

2

Answers


  1. Chosen as BEST ANSWER

    HERE IS THE SOLUTION!!

    My response needed to be converted from json to javascript object. It kept giving me undefined when I tried this.response.main.temp. The way I figured it out was the when I tried this.response[0], the result was a “{”. I was like, okay, so this must be unable to interpret this json as an object. It’s just a string of all the json characters. So I found json.parse() in order to turn it into a javascript object, and bam-- API ping success with the ability to access all the data.


  2. Alternatively, you could just change “requestType = “json”” to responseType = json…. instead of having to parse it into an object. It’s not requestType. It’s responseType.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search