0

I'm trying to get the JSON contents of a file via JSON, but I can't get it to work. My file tree looks like this:

  • root
    • js
      • script.js
    • json
      • data.json

I can't reach the data.json file from my Javascript script. Here's my code:

var data, request;
if (window.XMLHttpRequest){
    request = new XMLHttpRequest();
} else {
    request = new ActiveXObject('Microsoft.XMLHTTP');
}
request.open('GET', '../json/data.json'); // This works fine when the script is placed in the root and the ../ is removed, but when I move it into the js folder it breaks.
request.onreadystatechange = function() {
    if ((request.readyState == 4) && (request.status==200)) {
        var data = JSON.parse(request.responseText);

        if (data) {
            return data;
        } else {
            return "No data found";
        }
    }
}
request.send();

console.log(data);

The expected result is it returns an object from the JSON folder or print "No data found". Instead I just get undefined in my console. This means my only problem is actually finding that file. I don't normally use JavaScript so I'm probably just not using the right syntax, but since ../json/data.json clearly is incorrect, what is?

Sam Hill
  • 136
  • 1
  • 10
  • Ajax requires an url, not a relative path. If you're running your code on a server you should get the actual url of your json file like `http://localhost/json/data.json` – Ayrton Oct 25 '19 at 00:27
  • I tried `file:///Users/...path_to_root.../root/json/data.json` but it's not working. I'm not running it on a server. (On OS X) – Sam Hill Oct 25 '19 at 01:01
  • In that case, you should check for status 0 instead of 200. Reference: https://stackoverflow.com/questions/14446447/how-to-read-a-local-text-file/14446538 – Ayrton Oct 25 '19 at 01:05
  • That still didn't work. My new code: `...if ((request.readyState == 4) && (request.status==0)) {...` – Sam Hill Oct 25 '19 at 01:13
  • Check out the question I referenced. Also, try opening your url in the browser and see if it works – Ayrton Oct 25 '19 at 01:15
  • Yeah I'm doing everything in that question, and the URL does work. I updated my if statement to check for both 200 and 0 and it's still not returning anything. I put a console.log in the code and it just wont run – Sam Hill Oct 25 '19 at 01:22

0 Answers0