JavaScript AJAX Basics (retiring) Programming AJAX Processing JSON Data

Daniel Maldonado
Daniel Maldonado
15,673 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');