What is the best way to retrieve and store the contents of a .txt file that is accessible via HTTP into a JavaScript array,

I'm facing an issue where I have a .txt file accessible via http (for example, "", although not an actual link) and I am attempting to load it into a JavaScript array by lines using pure JavaScript. However, none of the solutions provided by others seem to be working for me. The explanations are unclear or insufficient for me to make necessary modifications.

Here are two solutions that I have come across which claim to work with raw JavaScript:

var openFile = function(event) {
    var input = event.target;
    var reader = new FileReader();
    reader.onload = function(){
        var dataURL = reader.result;
        var output = document.getElementById('output');
        output.src = dataURL;
    };
    reader.readAsDataURL(input.files[0]);
};

and

function readTextFile(file) {
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function () {
        if(rawFile.readyState === 4) {
            if(rawFile.status === 200 || rawFile.status == 0) {
                var allText = rawFile.responseText;
                alert(allText);
            }
        }
    }
    rawFile.send(null);
}

However, neither of these solutions actually returns the text content of the file in an array format where each cell represents an individual line from the text file. How can I achieve this?

EDIT: I tried modifying the second option as follows:

function readTextFile(file){
    var allText;
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function () {
        if(rawFile.readyState === 4) {
            if(rawFile.status === 200 || rawFile.status == 0) {
                allText = rawFile.responseText.split("\n");
                return allText;
            }
        }
    }
    rawFile.send(null);
}

Unfortunately, I encountered two errors:

Content Security Policy: Ignoring ‘x-frame-options’ because of ‘frame-ancestors’ directive.

and

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://foo.net/bar.txt. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

Upon debugging, I discovered that the program doesn't even reach the onreadystatechange section.

Answer №1

In the scenario you presented, the second example proposes a solution where you can transform it into an array by using the .split method at occurrences of \n. By executing allText.split("\n"), you will generate an array containing all the text elements separated by newlines.

It's important to note that the functionality of your second example is contingent upon whether the address is located on the same website as the page or if it is capable of bypassing CORS restrictions. This safeguard is crucial in preventing malicious activities such as unauthorized posting or actions being performed on your behalf without actually visiting the site in question.

To facilitate access to the text file via CORS, you can set the Access-Control-Allow-Origin header to * within the response configuration for your site.

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

Modify components in a web application based on the content of a JavaScript variable

I'm in the process of developing a webapp that needs to interact with an Arduino for its inputs in order to dynamically change the contents of the webpage. Currently, I am experimenting with variables that I have created and assigned random numbers t ...

rearranging nodes from multiple arrays into a single array and then repositioning them within the parent array using angularjs

[![enter image description here][1]][1]I am working with AngularJS and I have multiple arrays named list1, list2, and list3. Each array is used in a different list. Within my application, there are two buttons and two divs - the left div displays elements ...

Splitting elements into two categories with Angular.JS: Comparing ng-hide and filter

My task is to take an object with data and display it in two separate lists. The structure of the object is as follows: var data = [ {name: "Something 1", active: 1, datetime: "goes", author: "here"}, {name: "Something 2", active: 0, datetime: "goes ...

Exclude the file directory from the JavaScript output

This is what I currently have. The output that I receive is C./FAKE PATH/(value). What I actually want is just to display the value without including the C./FAKE PATH/. $('#inputid').change(function(){ var value = $(this).val(); alert(value) ...

Don't use onchange() in place of keyup()

Issue: I am facing a problem where the keyup() function is calling ajax multiple times with each key press, and I have tried using onChange() but it did not work as expected. Here is the code to check if an email already exists in the database: $.noConf ...

AngularJS modal directives trigger a reset of $scope variables

I am developing a custom AngularJS application that needs to handle and store all the checkbox selections made by the user in a simple array of IDs. The functionality includes displaying a modal when the open button is clicked, allowing the user to perform ...

Is there a way to load all movies in advance when none of the tags are selected?

In my current project, I am working on a feature that involves an array of movie objects. Each movie has a name and tags assigned to it. I want to be able to display movies based on the tags selected by the user. For example, if the user selects the tag "c ...

What is the method for updating state in React without relying on any events to trigger

I am trying to continuously update the value of a counter variable at fixed intervals in my code. Here is what I have so far: class Counter extends React.Component { constructor(props) { super(props); this.state = { myCount: 1 ...

Error parsing PHP string arrays into JavaScript string arrays

My attempts to convert a name string array from PHP to Javascript have been unsuccessful. var name = <?php echo json_encode($eventname); ?>; and var name = new Array("<?php echo implode('","', $eventName);?>"); I expected the ou ...

How to prevent v-menu from overlapping a navbar in Vue.js

Exploring the examples on the main page of Vuetify, we come across the v-menu component showcased in detail. Check it out here: https://vuetifyjs.com/en/components/menus/#accessibility If you activate any of the buttons to open the v-menu and then scroll ...

Creating a separation between Mongoose data access code and pure data objects in Node.JS using Object-Oriented Programming

I've stumbled upon a design dilemma regarding Mongoose - could it be that my approach is off? In the traditional OOP fashion, I aim to create a User class. This class includes various attributes such as username, firstname, lastname, salt, and hash, ...

The submission of the form with the ID "myForm" using document.getElementById("myForm").submit() is

<form name="formName" id="formName" action="" method="post" autocomplete="off"> <input type="hidden" name="text1" id="text1" value='0' /> <input type="button" name ="submit" onClick="Submit()" value="submit"> ...

Using javascript code to encode images to base64 and save the output to a text file

How can I modify the code below: <p id="demo"></p> <script> var openFile = function(event) { var input = event.target; var reader = new FileReader(); reader.onload = function(){ var dataURL = read ...

Converting HTMLCollection to a string: A step-by-step guide

I am currently developing a bot that is designed to modify a form on a website. One specific section of the form contains HTML content. My process involves extracting data from this section, converting it into an HTMLCollection object, performing some acti ...

What are some other popular JavaScript classes, aside from Set and Map, that do not cooperate well with JSON.stringify()?

After applying JSON.stringify to a Map or Set in JavaScript, the result is empty: console.log(JSON.stringify({foo: new Map([[1,2], [3,4]])})); The output is simply: {"foo":{}} To address this issue, one workaround is to use: console.log(JSON.stringify ...

transpile TypeScript code into ES6 rather than ES5

I am currently diving into typescript and I have observed that the code output always defaults to using var. Is there a way to make it output const and let in the .js file instead, or does typescript always require es5 output for some reason? Thanks. Her ...

Is it possible to develop a function that can verify various input values and modify their appearance as needed?

I am currently working on creating a form and faced with the challenge of simplifying my code using a function. Specifically, I want to write JavaScript code that will check all input fields in the form to ensure they are filled. If any field is left emp ...

Are you considering using requestAnimationFrame on your iPhone?

Can the requestAnimationFrame function be used on an iPhone running iOS 5.1? Based on my research, it seems that mobile Safari does not support this method, regardless of whether or not a vendor prefix is used. ...

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 ...

Mistakes in validating email form

I'm having some difficulties creating a basic contact form. I'm following the guidelines outlined in and the initial step involves using JavaScript to highlight the input box with a red border when invalid input is entered. Unfortunately, the ...