Unable to retrieve data from local file using ajax

While delving into the world of AJAX, I encountered an issue when trying to fetch data from a local file. An error related to CORS popped up, despite my attempts to solve it by installing the 'allow-access-control-origin' plugin. Any assistance with this problem would be greatly appreciated.

Below is a snippet of my JavaScript code:


    function loadData() {
        const xhr = new XMLHttpRequest();
      
        xhr.open('GET', '/data.txt', true);
      
        xhr.onprogress = function(){
          console.log('READYSTATE', xhr.readyState);
        }
      
        xhr.onload = function(){
          console.log('READYSTATE', xhr.readyState);
          if(this.status === 200) {
            document.getElementById('output').innerHTML = `<h1>${this.responseText}</h1>`;
          }
        }
      
        xhr.onerror = function() {
          console.log('Request error...');
        }
      
        xhr.send();
    }
    

The error output can be seen in this image: [link to error image][2]

Answer №1

To store data on your device, consider utilizing localStorage.

For retrieving data from a source, opt for a web service.
You could set up a basic web server with tools like Node and Express (numerous tutorials available online), however, this topic is not covered in detail here.

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

Improving Page Load Speed with HTML Caching: Strategies for Enhancing Performance when over half of the data transferred is for navigation menus

I manage a complex and expansive website that contains a significant amount of repetitive HTML elements such as the navigation menu and top ribbon. Loading a single page on my site can be resource-intensive, with up to 300KB of data required, half of whic ...

What is the best location to include my JavaScript code in WordPress?

Alright, so I've got this world map on one of my WordPress pages and here's an example of the code: <area onmousedown="modifyImage('world_map_01', './images/map/asia.jpg')" onmouseout="modifyImage('world_map_01', ...

Issue with fadeout() on absolutely positioned element loaded via AJAX in jQuery

Currently, I am utilizing AJAXify on a website project to implement page transitions and encountering some abnormal behavior with jQuery. Below is my code: HTML (I am transitioning through backgrounds using jQuery) <div id="backgrounds"> <img s ...

Reactjs: Could someone provide a more detailed explanation of this statement?

After reading this line in the documentation here, I came across an interesting code snippet. this.setState({ chats: [...this.state.chats, data], test: '' }); It seems like we are adding to the 'chats' array in the state, but I&ap ...

Clipped Words & Silhouettes

I'm having trouble ensuring the text in this particular example displays correctly. I am experiencing challenges with the clipping of text and shadows on certain letters, and I'm struggling to identify the root cause as well as the solution. In ...

Encountering an ExpressionChangedAfterItHasBeenCheckedError in Angular 6 when selecting an option from a dropdown menu

How can we fix the error mentioned below through code changes? Situation An input dropdown UI is safeguarded against unintentional value changes by a modal. However, triggering an event (such as click or focus) on the dropdown leads to the ExpressionChan ...

How can I display different data values on each individual circle counter, rather than all circles showing the same data?

Hey there! I'm trying to get my circular counters to display the counter value that I specify in their class and data-percent. However, currently all four counters are only showing the data from the first counter, even though I've set different d ...

What's the best way to handle variables and numerical calculations within PHP loops when dealing with forms?

I'm currently developing a basic PHP page where users can choose how many numbers they want to add together. After selecting the quantity, they input the numbers on a new page, click a button, and then see the sum displayed. The challenge I'm fa ...

Having trouble downloading a PDF file on a local server with React and the anchor tag element

Having trouble downloading a pdf file from my react app to my Desktop. I've reached out for help with the details How to download pdf file with React. Received an answer, but still struggling to implement it. If anyone new could provide insight, that ...

Tips on implementing a circular progress bar with locomotive scroll functionality

Can anyone help me integrate progress functionality with Locomotive Scroll using JavaScript? Link to CodePen for reference Check out this code snippet from Locomotive Scroll that calculates the percentage of pages scrolled: const scroller = new Locomotiv ...

What steps should I take to make my Vue JS delete function operational?

As I work on developing my website, I've encountered some challenges. Being new to coding, I'm struggling with creating a functional delete user button. When I click delete, it redirects me to the delete URL but doesn't remove the entry from ...

The Vue warning indicates that there was a failed type check for the "value" prop. It was expecting an array but received a number with a value of 1

I am facing an issue with an input of type number where I need to restrict the user from entering a number greater than ten. Initially, everything was working fine until I decided to change the value to an array (from value: 1 to value: [1, 1]) After swit ...

Dealing with Asynchronous Frustrations: Is it best to utilize callbacks and what is the most effective way to pass them across various

I am working on developing a straightforward text-based game that functions within a socket.io chat room on a node server. The structure of the program is as follows: At present, there are three key modules: Rogue: serves as the core of rogue game functi ...

The leaflet_Ajax plugin is constantly searching for the default marker symbol located at js/images/marker-icon.png

Although I'm relatively new to Leaflet, I have experience creating interactive maps in the past. Recently, I've been working on a project involving displaying GPS data from a UAV. The UAV transmits location information to a server, which then ret ...

Ordering an Array of JavaScript Objects in a Custom Sequence (utilizing pre-existing methods)

Imagine we have an array of objects: ["c", "a", "b", "d"] Is there a way in ECMAScript or through a third-party JavaScript library to rearrange the objects in the first array to match the order specified by the second array, all within one line or functi ...

Using three.js to maintain an object's position on top of another object's surface

I have created a terrain geometry using this JavaScript code: var geometry = new THREE.PlaneGeometry(100, 100, 100 , 100 ); for (var i = 0, l = geometry.vertices.length; i < l; i++) { geometry.vertices[i].z = Math.random() / 2; ...

What is the method for determining the size of a WeakMap?

I am working with a WeakMap that looks like the following: let newObj = new WeakMap(); let key1={"a":1}; let key2={"b":2}; let key3={"c":3}; newObj.set(key1,"value1"); newObj.set(key2,"value2"); newObj.set( ...

Exploring the concept of ng-model with undefined values in AngularJS

Having an input with a $watch function that updates a search query in real time through AngularJS, I am encountering an issue. Despite setting the initial value of the model to empty, it automatically triggers the search and displays results. My concern i ...

Reduce the version of NodeJs and express

At the moment, I am tackling a nodejs project. I have Express 3.X installed, which is currently in its alpha stage, and my node version is also at 0.7.2-pre. I am currently attempting to lower my express version through npm, but it appears that I also need ...

Conflict between jQuery and dynamically changing page content

I've come across multiple discussions on SO regarding similar topics, but I haven't been able to successfully troubleshoot my code to achieve the desired functionality. I'm currently working on an application that involves dynamically chang ...