JavaScript encounters difficulty in reading the text file

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?

Answer №1

In order to avoid "cross origin requests" errors, it is essential to run a web server and send the get request to a URI on that server, rather than directly requesting a file.

Make sure to update your code from:

humidgraph('public/sensordata.txt','chartContainer')

to something like:

humidgraph('http://localhost/public/sensordata.txt','chartContainer')

and ensure that the initial request page is also loaded from that same server.

Furthermore, follow these steps for your request in the correct sequence:

fileread.onreadystatechange=function (){
   ...
};
...

fileread.open("GET", datasource);
fileread.send();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The order of execution is not maintained for $.getJSON() calls within the $.each() loop

As I iterate through an HTML table, I am making a $.getJSON() request based on the data in each row. My goal is to retrieve the data from that $.getJSON call and update the corresponding row with it. Unfortunately, when I run my code, it seems to be execu ...

Can you pinpoint the issue with this asynchronous function in Vue3?

Dealing with a simple concept error, I find myself unable to solve it. Within the onMounted hook, everything looks correct - an Array of three objects is displayed. However, when I return it to the template and try to interpolate it, all I see is an empty ...

Unable to use the .focus() method on a Link component by utilizing references in React Router 4

I am currently working with the Link component in react-router (v4). I have successfully attached a ref to this component and can log the reference. However, when I try to use linkRef.current.focus(), I encounter the following error: linkRef.current.focu ...

Can using the jQuery.clone method impact other functions?

Assuming $dom is a jQuery element, can the following line be safely removed if a is not utilized thereafter? var a = $dom.clone(true,true); When using $dom.clone(false,false), it appears that there are no side effects. I believe this method doesn't ...

"Problem with AngularJS: Unable to display data fetched from resource using ng-repeat

I am currently working on an AngularJS application that retrieves data from a RESTful API using $resource. However, I have encountered an issue where the view is not updating with the data once it is received and assigned to my $scope. As a beginner in An ...

What is the best way to iterate over a multidimensional array in Angular/Ionic?

I've been struggling to find a solution tailored for looping in a .ts file instead of HTML. My main objective is to iterate over an array and compare the entered value with the keys. If there's a match, I want to retrieve the values stored withi ...

What is the purpose of using $ symbols within NodeJS?

Lately, I've been attempting to grasp the ins and outs of using/installing NodeJS. Unfortunately, I'm feeling a bit lost due to tutorials like the one found here and their utilization of the mysterious $ symbol. Take for instance where it suggest ...

Is there a tool available that can convert the string "foo:blah" into JSON format?

My goal is to transform a human-readable list like the following: Enabled: Yes Server: example.com Port: 8080 Authenticated Proxy Enabled: 1 ... into a sanitized JSON object as shown below: { "Enabled": "Yes", "Server": "example.com", "Port" ...

Learn the step-by-step process of clicking on a button to modify its properties and deactivate it

I could really use some assistance. I'm trying to make a button: <v-btn dark color="primary" class="square">Tile 1</v-btn> Is there a way I can modify it so that when clicked, it changes to flat, becomes disabled, and switches its color ...

Ways to customize the appearance of a react-chartist component

I recently created a React JS component that utilizes the amazing react ChartistGraph component. However, I've run into an issue where the default CSS of ChartistGraph seems to be conflicting with my custom styling. While there is plenty of documentat ...

Unable to fetch the identification number from the database

I'm encountering an issue with retrieving the ID from my database: Here is a snapshot of my database: Below is my event controller class: <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Event ...

Customize specific styles for individual divs one at a time (without the use of jQuery)

Can you assist me with this issue? I am trying to display the <span class="badge badge-light"><i class="fa fa-check-circle"></i></span> tag (initially set to "visibility: hidden") when clicking on a div with the class "role-box". He ...

How to manage multiple controllers for the same template in AngularJS?

I am facing a requirement where a single page needs to display a lot of different data, all within one vertical-scrolling page. To manage this, I have implemented collapsible divs on the page controlled by ng-if to efficiently handle the DOM elements. In ...

Retrieve information from a deep array structure

How can I extract the `id` from each marker's `routes` array in this JavaScript object while still referencing `item.id`? { "markers": [ { "id": "77475", "smsCode": "77475", "name": "Abbey Sports Centre" ...

When using the * selector in jQuery on Chrome, it targets and selects scrollbars

Here's the code I'm currently using: $("*").bind("mousedown.sg", { 'self':this }, this.sgMousedown); This code binds an event listener to all elements on the page, and it functions properly in most browsers except for Chrome. In Chrom ...

Mastering the art of scrolling and selecting items concurrently using the mouse in Vue

Struggling with a fascinating challenge of scrolling while selecting items using mouse drag in both up and down directions. Here's a screenshot for reference: https://i.stack.imgur.com/giMwY.png Check out my code: https://codesandbox.io/s/select-i ...

What can be done to resolve the slowdown caused by an Ajax request within the function?

I've implemented drag and drop functionality for saving images, but I'm facing an issue with getting an instant preview of the saved images. Whenever I try to send the image to the server using an ajax request, the image doesn't appear on th ...

I am unable to display my JSON data in Next.js using a fetch request

I'm having trouble understanding the code, and it seems like the API is open to anyone since it's just a simple JSON. However, I keep getting an error: Error Message: Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit th ...

Exploring the wonders of Onsen UI's ng-repeat feature combined

Facing a major issue with my app, and I suspect it's due to the asynchronous call. The HTML section looks like this: <ons-list ng-repeat="item in newsEventi.items"> <ons-list-header class="news_titolo_lista">{{item.categoria}}</ons ...

The application experiences crashes when the tablet is rotated, happening while in the development stage

For my web-based Android application project, I am utilizing PhoneGap and Eclipse IDE on a Windows platform. My focus is specifically on Tablet development, more precisely on the Samsung Galaxy Tab 10.1. To develop, I use Eclipse and test the app on the ...