1

I just want to display the first value of Port01 in Html. The corresponding JavaScript code for this.

<script>


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 inputData = loadFile("data123.js");
var sensorData = JSON.parse(inputData);
var valueData = sensorData[0].value;
document.getElementById("value").innerHTML = valueData;
</script>

<body>
    <div id="value" ></div>
</body>

and in addition data123.js file

[{"name":"VVB001 (port01)","time":"2021-02-10 14:01:09","type":"a-Peak","value":0.2},{"name":"VVB001 (port02)","time":"2021-02-10 14:01:09","type":"a-Peak","value":0.2},{"name":"VVB001 (port03)","time":"2021-02-10 14:01:09","type":"a-Peak","value":0}]

1 Answer 1

1

The problem here is that the following line:

result = xmlhttp.responseText;

gets executed before the response arrives. This is because of the asynchronous nature of the call, which you set with false in xmlhttp.send(). You should wrap the above line in an onreadystatechange listener:

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

var inputData = loadFile("data123.js");
var sensorData = JSON.parse(inputData);
var valueData = sensorData[0].value;
document.getElementById("value").innerHTML = valueData;

A side note: your JSON file has a .js extension.

Sign up to request clarification or add additional context in comments.

3 Comments

Then the JSON you are getting is invalid, as opposed to that you've posted in your question, which is valid.
other ideas maybe?
This is what can be deduced from your error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.