22

I want to read a .txt file an URL location, lets say from http://www.puzzlers.org/pub/wordlists/pocket.txt and process its content on my page.

Can you point me out some tutorials or some basic code on how to do this in javascript?

I have a basic HTML code where I have some tables and I want to populate them with text from a .txt from a given URL location, but I do not know how to read the data from that location.

<html>
<head>
  <title>Pseudoganglia Interface</title>
  <!-- CSS goes in the document HEAD or added to your external stylesheet -->
  <style type="text/css">
  table.gridtable {
    font-family: verdana,arial,sans-serif;
    font-size:11px;
    color:#333333;
    border-width: 1px;
    border-color: #666666;
    border-collapse: collapse;
  }
  table.gridtable th {
    border-width: 1px;
    padding: 8px;
    border-style: solid;
    border-color: #666666;
    background-color: #dedede;
  }
  table.gridtable td {
    border-width: 1px;
    padding: 8px;
    border-style: solid;
    border-color: #666666;
    background-color: #ffffff;
  }
  </style>
  <!-- Table goes in the document BODY -->
  <script>
    function getText()
    {
     // read text from URL location
    }
    function populateTables() {
      var tableHP = document.getElementById("tHP");
      // Create an empty <tr> element and add it to the 1st position of the table:
      var row = tableHP.insertRow(tableHP.rows.length);
      // Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
      var cell1 = row.insertCell(0);
      var cell2 = row.insertCell(1);

      // Add some text to the new cells:
      cell1.innerHTML = "NEW CELL1";
      cell2.innerHTML = "NEW CELL2";
    }
  </script>
</head>
<body onload="populateTables()">
<table class="gridtable" id="tHP">
  <tr>
<th colspan=2>HP</th>
  </tr>
  <tr>
<td># SN</td>
<td>% of used RAM</td> 
  </tr>
</table>

<br>

<table class="gridtable" id="tIBM">
  <tr>
<th colspan=2>IBM</th>
  </tr>
  <tr>
<td># CN</td>
<td>% of used RAM</td> 
  </tr>
</table>
</body>
</html>
thsknc
  • 19
  • 2
Simon
  • 4,999
  • 21
  • 69
  • 97
  • do you have control over the location which has this text file? – krishwader Mar 03 '15 at 09:22
  • 1
    The search term you are looking for is Ajax. The world doesn't need another Ajax tutorial (so voting to close as too broad). – Quentin Mar 03 '15 at 09:26
  • It's not too broad at all, it's just duplicate: http://stackoverflow.com/questions/15547407/javascript-read-text-file-using-ajax – CyberDude Mar 03 '15 at 09:33
  • @CyberDude — It doesn't look like a duplicate of that one, since the question has already found the XHR object and tried to use it. – Quentin Mar 03 '15 at 09:35
  • Maybe not 100%, there are plenty of similar questions, I just picked one. – CyberDude Mar 03 '15 at 09:40
  • I looked at about a dozen and couldn't find any I thought were actual duplicates of this one. – Quentin Mar 03 '15 at 09:42
  • I have tried the solution from the post mentioned by @CyberDude , however it's not working. It's not going inside this if `if (textfile.readyState == 4 && textfile.status == 200)` . Does it have something to do with Access-Control-Allow-Origin ? If so, how can I fix it? – Simon Mar 03 '15 at 09:44
  • The value of `textfile.readyState` is set to the value of `4` and `textfile.status` is set to the value of `0`. – Simon Mar 03 '15 at 09:46
  • @Simon — If it had something to do with Access-Control-Allow-Origin then you'd get an error message saying so. – Quentin Mar 03 '15 at 09:51
  • I don't think this is a duplicate at all. As I read it, the asker is looking for a simple way to read a text file from a URL - say, something like std.file.read in D or File.ReadAllText in .NET, or a file I/O (or just I) API similar to those found in most programming languages, but which uses a URL as an input source. – Stewart Jun 23 '19 at 16:07
  • Another idea, which maybe the asker was hoping exists, is a means of accessing the content of a file referenced in a tag from JavaScript. Loading the file would then be part of the process of loading the page, just like loading an image, JS file or CSS file is. In any case, this question isn't asking how to use a specific method for reading a file, thus isn't a duplicate of any question that is. Rather, the essence is one of "what approaches exist?". – Stewart Jul 27 '21 at 13:06

2 Answers2

22

this code may help you:

function getText(){
    // read text from URL location
    var request = new XMLHttpRequest();
    request.open('GET', 'http://www.puzzlers.org/pub/wordlists/pocket.txt', true);
    request.send(null);
    request.onreadystatechange = function () {
        if (request.readyState === 4 && request.status === 200) {
            var type = request.getResponseHeader('Content-Type');
            if (type.indexOf("text") !== 1) {
                return request.responseText;
            }
        }
    }
}
function populateTables(){
    
    var outer_text = getText();
    outer_text = outer_text.split('\n');    // you can adjust the manner of parsing the received file (regexp)
    
    var tableHP = document.getElementById("tHP");
// Create an empty <tr> element and add it to the 1st position of the table:
    var row = tableHP.insertRow(tableHP.rows.length);
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);

// Add some text to the new cells:
    cell1.innerHTML = outer_text[0];
    cell2.innerHTML = outer_text[1];
}
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
  • I am having the same issue as above. For `request.readyState` I get the value of `4` and for `request.status` I get the value of `0`. Do you know what might cause this and how should I fix it? – Simon Mar 03 '15 at 10:08
  • And for `var type = request.getResponseHeader('Content-Type');` I get `null`. – Simon Mar 03 '15 at 10:11
  • Probably, you don't have permissions to request resources from another domain (ES same origin policy). On "that" domain the following header should be set: header('Access-Control-Allow-Origin: *'); – RomanPerekhrest Mar 03 '15 at 11:18
  • 4
    I realize this is an old question now, but it was helpful to me so I'll add my observation as to why some may be having problems with it. The call to request.open includes `true` for asynchronous but the getText() function is being called with the assumption that the result will be present immediately. In my case, I called a separate function with request.responseText rather than returning it. Maybe passing false to request.open() might block until it's loaded. That could be an alternative fix. – Ken Lyon Mar 23 '17 at 22:26
22

from codegrepper using fetch (unsupported on IE).

const url = "http://www.puzzlers.org/pub/wordlists/pocket.txt"
fetch(url)
   .then( r => r.text() )
   .then( t => //process your text! )
Ian Campbell
  • 355
  • 2
  • 6