user14508088
user14508088

Reputation:

Unable to display the contents of a text file in an html webpage

I'm learning how to use html and javascript, and I've been trying to create a html webpage that gets the contents of a text file, info.txt, and displays it on the webpage as soon as the webpage is opened.

My problem is that the contents of the text file will not show up on the webpage. I've tried opening my html file on Chrome and FireFox, but the info.txt's contents won't show up. I'm storing the text and html files in the same folder.

I've attached my html code and info.txt. If anyone could give me some pointers on how to resolve this, I'd really appreciate it!

<!DOCTYPE html>
<html>
<body>

<h2>Info</h2>

<script type = 'text/javascript'>

function read_file() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      var e = document.getElementById('info');
      e.innerHTML = xhttp.responseText;
    }
  };
  xhttp.open('GET', 'info.txt', true);
  xhttp.send();
}
read_file();

</script>

</body>

</html>

info.txt:

Dan, Green Tea
Lola, Earl Grey
De, Matcha
Pearl, Coffee

Upvotes: 0

Views: 974

Answers (1)

Walker Sutton
Walker Sutton

Reputation: 390

You don't have any html element with an id="info".

var e = document.getElementById('info');

This is trying to find that element with the id, but there isn't one.

I think what you need to do is create some sort of element, maybe a paragraph element that has this id. <p id="info"></p>

Upvotes: 3

Related Questions