-1

I am trying to read a text file from folder where website is saved.

File is in the same folder as a class from which I try to read the file.

config.json (file which I am trying to read) contains:

{
"DATE": "Datum"
}

My code:

function loadFile(filePath) {
    var result = null;
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", filePath, false);
    xmlhttp.send();
    if (xmlhttp.status==200) {
      result = xmlhttp.responseText;
    }
    return result;
  }


  var myStuff = loadFile("config.json");
    console.log(myStuff);

output

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Dispečink</title>
    <link href='https://fonts.googleapis.com/css?family=Roboto:400,500,700' rel='stylesheet' type='text/css'>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  </head>
  <body>
    <div id="root"></div>
  <script type="text/javascript" src="/static/js/bundle.js"></script></body>
</html>

My problem is that I am getting output which i do not expect.

How to get correct data from config.json?

I have tryed to insert nonsensical path to loadFile() but still getting the same output

Bobek
  • 757
  • 3
  • 7
  • 15
  • 1
    `xmlhttp.open("GET", filePath, false);` — Syncronous requests are deprecated. Don't do that. – Quentin Aug 09 '18 at 08:09
  • 1
    You have failed to include a *clear problem statement*. You've just provided some code but not said what the problem with it is. – Quentin Aug 09 '18 at 08:09
  • *I have tryed to insert nonsensical path to loadFile() but still getting the same output* — What output is that? – Quentin Aug 09 '18 at 08:10
  • @Quentin I am trying to load data from config.json... output is **output**. In output are not data which are in config.json – Bobek Aug 09 '18 at 08:13
  • That HTML is the response? Then the problem is that your URL is wrong. Possibly there is no URL to the data you are trying to load. You need to find the correct URL or create a URL which will give you the data. The problem has nothing to do with the client side code. – Quentin Aug 09 '18 at 08:16
  • @Quentin yep, you are right – Bobek Aug 09 '18 at 08:17

1 Answers1

-1

You can use the oldschool XMLHttpRequest, but in my opinion it's far more convenient to use fetch these days, provided your browser is in this list.

Here is how you can use it:

function loadFile(filePath) {
  return fetch("/file.json").then(response => response.json())
}

Keep in mind that JS IO is asynchronous, and there are multiple ways to return async results:

  1. callbacks
  2. using promises

fetch uses promises. I highly recommend to get familiar with them.

I hope my answer is helpful! Good luck.

Anton Harniakou
  • 855
  • 6
  • 13