Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Help.

I am trying to retrieve data from open weather map and I keep getting this error: Uncaught SyntaxError: Unexpected end of input, below is my code.

<!doctype html>
 <html>
    <head>
        <meta charset="UTF-8">
        <script>
        var x1 = new XMLHttpRequest();
        x1.open('GET', 'http://api.openweathermap.org/data/2.5/weather?q=London');
        x1.onreadystatechange = function () {
            var w = JSON.parse(x1.responseText);
            var h = '<ul>';
            for(var i=0; i<w.length; i += 1){
                h += '<li>';
                h += w[i].temp;
                h += '</li>';
            }
            h += '</ul>';
            document.getElementById('box').innerHTML = h;
        }
        x1.send();
        </script>
    </head>
    <body>
        <div id="box">

        </div>
    </body>
</html>

3 Answers

Aaron Graham
Aaron Graham
18,033 Points

I think you are trying to parse the responseText into JSON before it is completely received. The way your code is currently structured, you are trying to parse responseText into JSON every time your x1 object changes states, not just when it has finished receiving data. Try adding a check for readyState in your callback:

x1.onreadystatechange = function () {
  if(x1.readyState === 4) {
    var w = JSON.parse(x1.responseText);
    var h = '<ul>';
    for(var i=0; i<w.length; i += 1){
      h += '<li>';
      h += w[i].temp;
      h += '</li>';
    }
    h += '</ul>';
    document.getElementById('box').innerHTML = h;
  };
}

You might also want to check for the response status code.

Also, depending on what you get back from the server, your for loop might not work. The variable w is going to be an object, and as such, might not have a .length attribute. Sometimes APIs will return a single object if you request a single item, or an array of objects if you request a collection of items. You might want to find out what the structure of the JSON response looks like to be sure there isn't a better way to extract the .temp attribute.

You appear to be missing a semicolon on line 18. Right before the line that says x1 = send();. Since the function is being assigned to x1.onreadystatechange, you need to be sure to close the assignment with a semicolon. Hope that helps!

Thanks!