Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript AJAX Basics (retiring) Programming AJAX Processing JSON Data

Daniel Maldonado
Daniel Maldonado
18,756 Points

JSON.parse(xhr.responseText) giving me an error

JSON.parse(xhr.responseText) is not giving me the desired result like Dave's video. I can tell that it's a type of 'String' but if I parse it, I get the error. I can console log(xhr.responseText) and can see my JSON object, but obviously that's not returning anything back to me if I try to display it on my web page.

Here's what I have, and just totally unsure where I'm screwing up;

var xmlRequest = new XMLHttpRequest();

xmlRequest.onreadystatechange = function(){
  "use strict";
  if(xmlRequest.readyState === 4){
      //console.log(xmlRequest.responseText);
      var text = JSON.parse(xmlRequest.responseText);
      console.log(text);
  }
};

xmlRequest.open("GET", "status.json");
xmlRequest.send(); 

Can someone take a peak and see where this is going wrong and/or maybe why it's not working? Again, if I don't use the JSON.parse() I can console.log the JSON object. and if I console.log the typeof object, console returns string. JSLint also shows that my JSON is valid so I'm just not sure what I'm missing.

Daniel Li
Daniel Li
15,244 Points

If your workspace is setup the same as mine, your GET request does not point to a JSON file. The following is what works for me.

xmlRequest.open('GET', 'data/employees.json');