Attempting to open and display the contents of a text file (.txt) within a modal dialog box upon clicking a button

I am attempting to develop a modal that will appear when the user clicks on a specific button. The goal is for this modal to showcase text retrieved from a separate file stored on the server. My aim is to show this text within a dialog box modal.

So far, I have tried linking the file directly, but unfortunately, the text from the file did not display inside the modal. Another approach I attempted was data-binding with a text observable, however, this method is relatively new to me.

<div class="logs">
     <button type="button" id="btn2" data-toggle="modal" 
    data-target="#openLog" data-bind="click: GetLog">Whoosh</button>
</div>
<!--n--> 
 <!-- Trigger/Open The Modal -->
   <!-- The Modal -->
 <div id="repModal" class="modal2">

 <!-- Modal content -->
 <div class="repmodal-content">

 <div class="repmodal-header">
 <h2 style="color:white;">Whoosh<style></style></h2>
 </div>
 <div class="remodal-headercontent"></div>
 <div class="repmodal-body" id="logText">
   <span data-bind="text: observable"></span>
   <span class="repclose">Close</span>
</div>
</div>

</div>


<!--Javascript--> 

<script>
// Get the modal
var modal = document.getElementById("repModal");

// Get the button that opens the modal
var btn = document.getElementById("btn2");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("repclose")[0];

// When the user clicks the button, open the modal 
btn.onclick = function() {
  modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it

window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

</script>

Answer №1

If you want to achieve that functionality, you can utilize XMLHttpRequest.

(For more detailed information on how to use XMLHttpRequest, visit: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)

Check out this operational example:

// Accessing the modal
var modal = document.getElementById("repModal");

// Retrieving the button that triggers the modal
var btn = document.getElementById("btn2");

// Getting the <span> element used to close the modal
var span = document.getElementsByClassName("repclose")[0];

// When the user clicks the button, display the modal 
btn.onclick = function() {
  modal.style.display = "block";
  let url = "https://baconipsum.com/api/?type=meat-and-filler&format=html";
  var request = new XMLHttpRequest();
  request.onreadystatechange = function() {
    if (request.readyState == 4){
      if (request.status == 200){
        document.getElementById("modal_text").innerHTML = request.responseText;
      } else {
        //handle error
      }
    }
    
  };
  
  request.open('GET', url);
  request.send();
}

// Close the modal when the user clicks on <span> (x)
span.onclick = function() {
  modal.style.display = "none";
}

// Close the modal when clicking anywhere outside it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}
<div class="logs">
     <button type="button" id="btn2" data-toggle="modal" 
    data-target="#openLog" data-bind="click: GetLog">Whoosh</button>
</div>
<!--n--> 
 <!-- Trigger/Open The Modal -->
   <!-- The Modal -->
 <div id="repModal" class="modal2">

 <!-- Modal content -->
 <div class="repmodal-content">

 <div class="repmodal-header">
 <h2 style="color:white;">Whoosh<style></style></h2>
 </div>
 <div class="remodal-headercontent"></div>
 <div class="repmodal-body" id="logText">
   <span data-bind="text: observable" id="modal_text"></span>
   <span class="repclose">Close</span>
</div>
</div>

</div>


<!--Javascript--> 

Answer №2

To retrieve the text content, use an XMLHttpRequest.

document.getElementById("btn2").addEventListener('click', () => {
    let request = new XMLHttpRequest();
    request.onreadystatechange = function () {
        if (request.readyState == XMLHttpRequest.DONE) {
            if (request.status == 200) {
                // If the request is successful, append the response text to a modal.
                let textElement = document.create("div");
                textElement.innerHTML = request.responseText;
                modal.appendChild(textElement);
            } else {
                // Handle gracefully in case of failed request
            }
        }
    };
    request.open("GET", URL_OF_TEXT_FILE, true);
    request.send();
}, false);

Note: Use addEventListener() to link this functionality to the button.

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

Why isn't the image showing up on my webpage when it's hosted in lite-server on localhost?

When the index.html file is opened normally, the image is displayed However, when hosted on a lite server, the image does not appear Check out the HTML code and directory of all the files An error message of 404 for the image file is being received Her ...

Is it possible to upload files without using AJAX and instead through synchronous drag-and-drop functionality in the foreground?

Currently, my website has a standard <input type="file"> file upload feature that sends data to the backend upon form submission. I am looking to enhance the functionality of the form by allowing users to drag and drop files from anywhere within the ...

What is the best way to handle errors in a forked child process?

Node.js version 8.11.1 We have a scenario with two files: parent.js and child.js. Parent Script const { fork } = require('child_process'); const forked = fork('./child'); forked.on('message', (msg) => { console.log(& ...

ajaxform is not providing the correct response

There is a form below that logs into Instagram based on the response it receives. If the login is successful (returns "ok"), then it shows success, otherwise it should display an error state. However, in my case, it always returns a null state for some un ...

Tips for activating a sticky navigation button by scrolling down slightly

Currently in the process of developing a website using React and focusing on optimizing the mobile version first. One feature I am working on is to have a sticky navigation bar that remains at the top after scrolling down. In the attached picture, there is ...

Passing the value of an Angular component to a different component

I have a menu in my application that uses IDs to route content, and I also have a detailed view where the content should be displayed based on those same IDs. Currently, I am trying to display objects by their ID when a button is clicked. However, I' ...

I'm looking to make my PayPal donate button smaller after noticing that PayPal is making it larger. How can I adjust the size of my customized PayPal

I am seeking your help in resolving an issue with PayPal enlarging my button from 130px x 65px to 300px x 150px. I have checked the button on both a local browser and within the Square Space editor, but the result remains the same. I even attempted to adju ...

MacOS web browsers adjust content to fit the screen size

As I delve into React development, one thing that has caught my attention is how MacOS browsers try to fit all the page content in view rather than allowing users to scroll. Let me illustrate this with an example: function Example() { const Elements = ...

What is the best way to dynamically adjust the width of multiple divisions in Angular?

I am currently working on an angular project to create a sorting visualizer. My goal is to generate a visual representation of an array consisting of random numbers displayed as bars using divisions. Each bar's width will correspond to the value of th ...

Using Jquery to dynamically add or remove a class based on scrolling behavior

Can someone help me with identifying the position of an element so that when the user scrolls to it and it appears on the screen, an icon can be highlighted? Currently, the script I am using adds the class too early, closer to the bottom of the block. I w ...

What is the best way to create space between three columns in Bootstrap?

Despite my efforts to find a solution on Stackoverflow, I have not been able to locate exactly what I need. I am trying to evenly space and center three columns across my page. However, when I assign col-md-4 to each column, they end up too close together ...

"Padding has not been recognized as a valid input value

I'm struggling with getting padding to be accepted by the browser when I style a card using Material-UI. const useStyles = makeStyles((theme) => ({ cardGrid: { padding: '20px auto' }, })) Unfortunately, the browser is not recogni ...

How can I align an image and text alongside another image using HTML and CSS?

Having some trouble positioning an Image and Text next to another Image. Check out an example here: I attempted using floats, but it doesn't seem to be working. Here is the code I have: .left {float: left;} .right{float: right;} <div class="left ...

The error message "props.text is undefined in React Native" indicates that there is an issue with accessing the property text within

//**// import { StatusBar } from 'expo-status-bar'; import {StyleSheet, Text, View, Button, TextInput, ScrollView, FlatList} from 'react-native'; import {useState} from "react"; import GoalItem from "./components/GoalItem"; export defau ...

My CSS is giving me a bit of trouble with alignment

I have been experimenting with various approaches such as adjusting the size of the divs to tiny dimensions and trying out inline-block or float left and right properties, but I am still unable to achieve the desired result of having my divs positioned s ...

What is the process for sorting Google Map markers with AngularJS?

.controller('MapCtrl', ['$scope', '$http', '$location', '$window', '$filter', '$ionicLoading', '$compile','$timeout','$ionicPopup', function ...

The AngularJS script is throwing an error that states "ReferenceError: Invalid left-hand side in assignment

While attempting to establish a connection with a webservice, I made an attempt using AngularJS $http option. However, when testing it out, I encountered an error in the console of my Chrome browser: ReferenceError Invalid left-hand side in assignment. Des ...

The jQuery function is returning an inaccurate value for the height of

In my Cocoa (Mac) application, I am utilizing a Webview and trying to determine the accurate height of a document. While the typical method webview.mainFrame.frameView.documentView.bounds.size.height works well in most cases, I encountered an issue with on ...

What is the most effective method for generating dial images through programming?

Currently, I am in the process of creating a website that makes use of variously sized and styled dials to indicate progress. The filled portion of the dial represents how close an item is to being 100% complete. I am seeking a universal solution that wil ...

Problem with redirecting when using HTTPS

I recently implemented an SSL Certificate and made changes to the web.config file. Here is the updated code: <system.webServer> <rewrite> <rules> <rule name="removed by me" stopProcessing="true"> ...