Using the 'get' command to read a text file locally in JavaScript

I am struggling to use the get command in JavaScript to open a text file and populate a div tag in my HTML. The text file is located in the same folder as my html file, but I can't seem to make any progress with this task. When I click on the button I created, I want it to change the content of the div tag.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html>
    <head>
<title>Glorious Final </title>
<meta name="keywords" content="" />
<meta name="description" content="" />
    <link rel="stylesheet" href="css.css" type="text/css" media="screen" charset="utf-8"/>

    <script src="jquery-1.4.4.min.js" type="text/javascript" charset="utf-8"></script>


    <script src="script.js" type="text/javascript" charset="utf-8"></script>
    </head>
    <body>

<div id="six-point-star"></div>
<h1>JQuery Jedi </h1>

<div id="ornamentRow1"></div>

<p>
<h2>Ajax  Admiral</h2>
<div id="ornamentRow2"></div>
</p>
<h3>Javascript Janitor</h3>
<div id="custom"></div>

<h4>
    <button type="button" id="twinkle" >Twinkle Me Starmo</button>

    <button type="button" onclick="hangOrnament1()">Hang First Ornament</button>
    <button type="button" onclick="">Hang More Ornaments</button>

</h4>

<h5>

    <button type="button" onclick="">!!Open Me!!</button>

</h5>

    </body>
    </html>

This is the JavaScript function that I want to use from the script.js file, but I believe the issue lies in the "GET" line at the end of this code snippet:

    function hangOrnament1()
    {
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
     xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("ornamentRow1").innerHTML=xmlhttp.responseText;
    }
    }
    xmlhttp.open("GET","ornaments.txt",true);
    xmlhttp.send(null);
    }

I have been researching forums for a solution for hours, but I can't find a fix for the issue. If anyone has insight into how I can correct this problem, I would greatly appreciate it.

Answer №1

To implement this functionality in your web application, utilize the provided jQuery script below. It is recommended to ensure that the --allow-file-access-from-files setting is enabled if you are using Google Chrome. Assume there is a paragraph or div element with an id of "Para1".

let result = "";
$.get('./ornaments.txt', function(data) {    
    let lines = data.split("\n");

    $.each(lines, function(index, element) {
                       s=s+"<br/>"+element;
             });
});
$("#Para1").html(result);

`

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

Gathering information from various web pages simultaneously without the need to manually navigate through each page using a webdriver

I'm new to the world of web scraping and I've successfully developed a program that allows me to extract specific, dynamic data by utilizing the selenium web driver. My current project involves scraping data from a FAQ page in order to gather in ...

Is :before functionality not compatible with img tags?

Is there a way to use the :before selector in CSS to overlay an image on top of another image? I have tried implementing it, but it seems that placing an image before an img element doesn't work as expected. Here is the CSS code I am using: .containe ...

Issues with THREE.js loading materials onto objects

Previously, I used mtl+obj files in an iOS app to load a 3D PCB chip into a scene. However, when trying to load it using three.js (r80), the object loads fine and the geometry appears correct, but none of the textures, colors, or images load onto the obje ...

Chart.js malfunctioning - Uncaught reference error:

In an attempt to visualize time series data using chart.js, I am encountering some issues. The data is extracted from a psql database, converted to JSON format, and then passed as a parameter to a JavaScript function for rendering the chart. Although the ...

Emulating a form submission using a jQuery AJAX request

I am working with a block of code that defines div elements as well as their click callbacks. In order to prevent repetition in my code, I am looking to reuse it. Currently, the callbacks are utilizing $.post calls to interact with the server, but on this ...

What is the method for showing the comment associated with a particular row that I wish to modify?

A commenting system is being implemented using jQuery, Ajax, PHP, MySQL, and HTML. There seems to be an issue where clicking the Edit button displays the comment of the first row in the MySQL table instead of the selected row. However, after editing, it do ...

Data in JSON format is not sourced from a text file

My latest project involved creating two new files within a folder titled "hello". These files are named index.html and jsontext.txt. The contents of index.html look like this: <!DOCTYPE html> <html> <head> <title>Experiment< ...

Disabling the loading of JavaScript on a Magento website

Seeking advice - I'm experiencing a delay on my website due to 3 unnecessary javascripts that are being loaded. Is there a way to prevent these scripts from loading or being searched for? Listed below is the website log where I am unable to locate jq ...

"Maximizing the power of Jquery's .each function. What

In my jQuery code, I have the following: function lshow() { var delayt = 500; var showtime = 5000; var ArrayOfElements = ['.slogan1','.whatwedo','.ekon','.ene', '.ekol', '.sm&a ...

When the Reload button is pressed, are ajax requests initiated by the page cached invalidated?

What occurs when the reload button on a browser is pressed and there are cached ajax calls executed at jQuery document ready? Will you receive a cached version, or will the cache be invalidated due to the Reload button being pressed? Additionally, does the ...

Performing a search through a string array and updating a specific portion of each string

I am faced with an array containing a long list of Strings, and my goal is to filter out all the strings that begin with 'INSERT ALL' and replace the number inside the parentheses with the string ' NULL' Here is the original array: le ...

I'm encountering an issue when trying to send a list of data to MVC

I am working with the following model: public class CompanyDto { public string CompanyName { get; set; } public IEnumerable<CompanySocialNetworkTypeDto> CompanySocialNetworkTypeList { get; set; } } public class Compan ...

Is there a way to set up an automatic pop-up for this?

Experience this code function AutoPopup() { setTimeout(function () { document.getElementById('ac-wrapper').style.display = "block"; }, 5000); } #ac-wrapper { position: fixed; top: 0; left: 0; width: 100%; height: 100%; back ...

Transform the binary image data sent by the server into an <img> element without using base64 encoding

It's been a challenge trying to find a reliable method for adding custom request headers to img src, so I'm experimenting with manually downloading the image using ajax. Here is an example of the code I am working on: const load = async () => ...

What is the method for connecting a button in one component to a div in a different component within a reactjs application?

I am in the process of developing a ReactJS application that consists of multiple components such as a navbar, hero section, form, and footer. My goal is to have a button in the navbar that, when clicked, scrolls down to another component (the form) with ...

The recently introduced button following an ajax request fails to trigger the expected event

How can I ensure jQuery still works after adding a new button with AJAX? $('button.btn').on('click', function(form) Here is a sample existing button on initial page load: <button id="5" class="yellow-button btn">Publish</but ...

Concealing Redundant Users in Entity Framework

I am faced with the task of sorting through a database containing over 4000 objects, many of which are duplicates. My goal is to create a new view that displays only one instance of each element based on the first and last name. I have already implemented ...

Verify whether a string concludes with the specified target strings | utilizing JavaScript

Looking to develop a JavaScript function that checks if the last characters of a string match a given target. The function must utilize the .substr() method for this purpose. function endOfString(str, target) { let endCharacters = str.substr(-target.l ...

Using React.js to create a search filter for users

When using useEffect with fetch(api) to set [search], I encounter an issue where "loading..." appears each time I enter something in the input box. To continue typing, I have to click on the box after every word or number. I am seeking advice on how to pr ...

What is the most effective method for accurately tallying the number of matches in a Datalist using the Input value as a reference

I have set up a datalist element with an associated input element for autocompletion in modern browsers: HTML code <input type="search" id="search" list="autocomplete" /> <datalist id="autocomplete"> <option value="c++" /> < ...