I can't get the JSON data!


I’m sure there is something silly I’m missing, but I figured after a month of youtube videos and looking at other peoples code, it was time to just ask. Once I can extract the JSON data I can work on everything else. HUUUGE thanks in advance, this has had me stuck for some time. I JUST WANT THE JSON!

Hey. You might want to send that request. Otherwise nothing will come up! You can also set a responseType, so you won’t have to parse the json.

  var requestData = new XMLHttpRequest();
  requestData.open('GET', "url");
  requestData.responseType = 'json'; // Set response type
  requestData.onload = function () {
    var weatherData = requestData.response; // Get response instead of responseText
    displayData.innerHTML = weatherData;
  }
  requestData.send(); // Send the request

HTML

<button id="buttonData">Get JSON</button>
<div id="displayData"></div>

JavaScript

var buttonData = document.getElementById("buttonData");
var displayData = document.getElementById("displayData");

buttonData.addEventListener("click", getData);

function getData(){
  var xhr = new XMLHttpRequest();
	
  xhr.open('GET', "https://api.openweathermap.org/data/2.5/weather?lat=43&lon=-117&appid=ebfb4d9156ffea185bac79a070d0829c", true);
	
  xhr.onload = function() {
		if(this.status === 200) {
			displayData.innerHTML = this.responseText;
		} else if(this.status === 404) {
			displayData.innerHTML = "Not Found";
		}
  };
	
	xhr.send();
}

Million thanks, glad there are people willing to help :smile:

1 Like