0

I'm attempting to get some data from the OpenWeatherMap API. When I send the request with the required API key and location data, everything returns back fine. The returned data appears to be in JSON format. However, when I perform the JSON.parse() function on the string, it gives an error of "unexpected end of input".

One thing that I found interesting was that if I was to store the string into a variable and then proceed to execute the function in Chrome's debug console, it completes fine.

let jsonData;
let jsonActual;
function GetWeather(city, country){
  Http = new XMLHttpRequest();
  Http.open("GET", weatherUrl + city + "," + country + weatherKey);
  Http.send();
  Http.onreadystatechange=(e)=>{
    jsonData = Http.response;
    jsonActual = JSON.parse(jsonData.toString());

  }
}

On using the console:

x = JSON.parse(jsonData) // Completes successfully
  • You're not checking the `readyState` in your `onreadystatechange` event handler. The response will only be complete when [`readyState`](https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState) is `complete`. – Heretic Monkey Mar 27 '19 at 23:38

2 Answers2

1

In your function onreadystatechange you have

Http.onreadystatechange=(e)=>{
    jsonData = Http.response;
    jsonActual = JSON.parse(jsonData.toString());

  }

Try to do this instead:

Http.onreadystatechange=(e)=>{
    if (this.readyState === 4) {
         jsonData = Http.response;
         jsonActual = JSON.parse(jsonData.toString());
    }

  }
Luis Barajas
  • 478
  • 3
  • 12
1

Your readyState is never checked if it is complete:

Http.onreadystatechange = e => {
    if (this.readyState == "complete") {
        jsonData = Http.response;
        jsonActual = JSON.parse(jsonData.toString());
    }
}

You could also check against 4:

Http.onreadystatechange = e => {
    if (this.readyState == 4) {
        jsonData = Http.response;
        jsonActual = JSON.parse(jsonData.toString());
    }
}

And you could just make it even simpler and use fetch:

let jsonData;
let jsonActual;
function GetWeather(city, country){
    fetch(`${weatherUrl}${city},${country}${weatherKey}`).then(res => res.json()).then(res => {
        jsonData = res;
        jsonActual = JSON.parse(res);
    });
}
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79