I am working on a project where I need to read a local text file located at /home/myname/Desktop/iot/public/sensordata.txt using JavaScript when a button is clicked on a web page. Below is the code snippet I have been using:
<html>
<head>
<title>Humidity</title>
</head>
<body>
<h3>Humidity page</h3>
<table>
<tr>
<td>
<button type="button" onclick="humidgraph('public/sensordata.txt','chartContainer')">View live humidity data</button>
</td>
</tr>
</table>
<p><div id="chartContainer" style="height: 300px;width=100%;"></div></p>
<script type="text/javascript">
function humidgraph(datasource,divid){
var i = 0;
var xVal, yVal;
var humidity = [], time = [], dps = [];
var fileread = false;
var obj = document.getElementById(divid);
if (window.XMLHttpRequest){
fileread = new XMLHttpRequest();
} else if (window.ActiveXObject){
fileread = new ActiveXObject("Microsoft.XMLHTTP");
}
if (fileread){
fileread.open("GET", datasource);
document.getElementById("chartContainer").innerHTML = fileread.responseText;
}
fileread.onreadystatechange = function(){
if ((fileread.readyState === 4 || fileread.readyState === 0) && fileread.status === 200){
var text = fileread.responseText;
text.split(/\n/).forEach(function(item){
humidity.push(Number(item.match(/Humidity(.\d+[.]\d+)/)[1]));
});
text.split(/\n/).forEach(function(item){
time.push(Number(item.match(/time(.\d+[.]\d+)/)[1]));
});
}
}
while (i < time.length){
xVal = time[i];
yVal = humidity[i];
dps.push({x: xVal, y: yVal});
i++;
}
}
</script>
</body>
</html>
Although I am using innerHTML, no data is being displayed on the html page. I suspect there might be an issue with my file path. Can someone please assist me with this problem?