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

What is the best way to divide an array into pairs and store them in separate arrays?

I'm attempting to challenge my JavaScript skills and faced with a dilemma. There is an array containing data var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];. The goal is to pair the elements and generate a new array of arrays such as var newArray = [[1 ...

The Sequelize error message states: TypeError: an array or iterable object was expected, but instead [object Null] was received

I am encountering an issue with the findOne method from sequelize in my model. The error message I am getting states that the table referenced by the model is empty. How can I resolve this? Unhandled rejection TypeError: expecting an array or an iterable ...

JavaScript data manipulation: Determining percentage change within a nested JSON structure

Provided is a JSON file structured like this... data =[ { key: "london", values: [ {day: "2020-01-01", city: "london", value: 10}, {day: "2020-01-02", city: "london", value: 20}, {day: " ...

Issue with Ng-style not functioning properly when setting background color

I am struggling to set the background of an element using a configuration object with ng-style. For some unknown reason, I can't seem to make it work and I'm finding it really perplexing. The element I'm attempting to configure: <div id ...

generate a series of nested divs within one another

I am looking to create a custom nested loop that will generate div elements based on the content of my h1 and h2/h3 tags. I understand this may have been covered in other inquiries, so any guidance would be appreciated :) Here is the initial HTML: <h1& ...

Refreshing HTML Form upon Submit using JavaScript

I've been searching through various discussions without any luck, but I'm encountering an issue with a form that successfully submits data to a Google Sheet, yet the input fields retain their content after submission. Here is the code: <form ...

The type '{ children: Element[]; }' does not include the properties 'location' and 'navigator' that are present in the 'RouterProps' type

Struggling to implement React Router V6 with TypeScript, encountering a type error when including Routes within the `<Router />` component. The error message indicates that the children property passed to the Router is of an incorrect type, despite u ...

Unlocking bundles of worth through javascript coding

Is there a way to retrieve a set of values using javascript? Upon page load, I am looking to display an alert showing the value '0-1' for any checked checkboxes. View example here var checkBoxes = document.getElementsByName('mailId[]&apos ...

What is the proper way to insert a line break within a string in HTML code?

Trying to simplify my code, I've turned to using Nunjucks to pass a group of strings to a function that will then display them. This is what it looks like: {% macro DisplayStrings(strings) %} {% for item in strings %} <div>{{ item.strin ...

Issue encountered while installing npm via command line

Currently in the process of installing node on my Mac and encountering an error. I downloaded Node from the official website and executed the package, but I am still facing issues. Can anyone advise me on why this error is occurring when I attempt to run ...

Attempting to incorporate Font-Awesome Icons into the navigation bar tabs

As a newcomer to React, I've been attempting to incorporate Font Awesome icons into my secondary navigation bar. Despite using switch-case statements to iterate through each element, all the icons ended up looking the same, indicating that only the de ...

Verify the placement within the text box

Are there methods available in JavaScript or any JavaScript framework to determine the position within a textbox? For example, being able to identify that figure 1 is at position 2 and figure 3 is at position 3. Figure 1 Figure 2 ...

How can I adhere to Angular 2's naming convention for Input and Output as suggested by the styleguide?

Working with inputs and outputs while following Angular 2's styleguide naming convention Initially, my directive was defined like this: ... inputs: [ 'onOutside' ] ... export class ClickOutsideDirective { @Output() onOutside: EventEmitter ...

"Easily toggle the visibility of values in checkboxes and organize them into groups with the power of JavaScript

Hey there! I am currently working on a project that involves grouping checkboxes and hiding/unhiding their content based on user interaction. Essentially, when the page first loads, the "All CARS" checkbox will be checked by default. If I then check the "C ...

Alerts in online software when there is a modification in the database

I am working on a project to create a web application that needs to display notifications, like the ones you see on Facebook, whenever there is a new update in the database. I could use some assistance with implementing this feature. Are there any third- ...

Encountering an issue with React Redux and Typescript involving the AnyAction error while working on implementing

While integrating redux-persist into my React project, I encountered an error. Previously, Redux was working smoothly, but upon the addition of redux-persist, I started receiving this error message: Types of property 'dispatch' are incompatib ...

Transmitting information in segments using Node.js

Recently delving into the realm of nodejs, I find myself tackling a backend project for an Angular 4 application. The main challenge lies in the backend's sluggishness in generating the complete data for responses. My goal is to send out data graduall ...

Unlocking Extended Functionality in JQuery Plugins

At the moment, I am utilizing a JQuery Plugin known as Raty, among others. This particular plugin typically operates as follows: (function($){ $.fn.raty = function(settings, url){ // Default operations // Functions ...

Is Typescript the Ultimate Replacement for propTypes in React Development?

After diving into Typescript for the first time and exploring related articles, it appears that when using Typescript with React, propTypes definitions may no longer be necessary. However, upon examining some of the most popular React Component Libraries: ...

The integration of Raphaeljs library with SmartPhones opens up a world of

I recently incorporated the incredible JavaScript library, RaphaelJS, into my website to create maps, animations, and interactive features. Interestingly, I have observed that the scripts utilizing this library function seamlessly on iPhones but encounter ...