17

When I go to a url like this: http ://my.url.com/file.txt, the browser shows text.

I would like a simple javscript command that does the following:
1. go to the url
3. take the text that shows up on the screen
4. store it in a variable for further processing

so something like

var url = http: //my.url.com/file.txt;

//some code here that goes to the url

//some code that takes said info and does something like:

var fileInfo = ---content of file.txt---

Note that the info I seek from the txt file is in html tags

<p>Text I need in Variable</p>

Any assistance would be greatly appreciated!
Thank you!

Aryeh K
  • 311
  • 1
  • 2
  • 8
  • Possible duplicate of [HTTP GET request in JavaScript?](http://stackoverflow.com/questions/247483/http-get-request-in-javascript) – Calum Sep 28 '16 at 21:35
  • or you could use PHP http://php.net/manual/en/function.file-get-contents.php – Baruch Sep 28 '16 at 21:36
  • Duplicate of http://stackoverflow.com/a/8567146/5053667 – Darren H Sep 28 '16 at 21:39
  • 1
    Possible duplicate of [How do I load the contents of a text file into a javascript variable?](https://stackoverflow.com/questions/196498/how-do-i-load-the-contents-of-a-text-file-into-a-javascript-variable) – wesinat0r Oct 14 '19 at 01:03

4 Answers4

14

Use the Fetch API.

Play with it at jsfiddle.net.

var url = 'https://fiddle.jshell.net/robots.txt';
var storedText;

fetch(url)
  .then(function(response) {
    response.text().then(function(text) {
      storedText = text;
      done();
    });
  });

function done() {
  document.getElementById('log').textContent =
    "Here's what I got! \n" + storedText;
}

Here's a smaller ES6 example that separates fetching from storing and showing off the result.

fetch('https://fiddle.jshell.net/robots.txt')
  .then((response) => response.text().then(yourCallback));

function yourCallback( retrievedText ) { /* . . . */ }

Adoption is already across the board.

You don't have to wait. Most people don't. You shouldn't.
GitHub provides a polyfill of those who can't upgrade.

What's better about fetch than XHR? ... Lots.

TylerY86
  • 3,737
  • 16
  • 29
  • 1
    Disclaimer: _Fetch support is at a fairly early stage, but progress is being made. It is turned on by default in Firefox 39 and above, and Chrome 42 and above._ – Gilles Quénot Sep 28 '16 at 21:51
  • For older browsers or people that refuse to update; https://github.github.io/fetch/ – TylerY86 Sep 28 '16 at 21:55
  • Thank you very much for your response, but this is the error I am getting when running this in a blank console: Fetch API cannot load http:// www.my-sample-url.com/file.txt. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'chrome://newtab' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. undefined:1 Uncaught (in promise) TypeError: Failed to fetch(…) – Aryeh K Oct 05 '16 at 17:26
  • You're fetching from a modification to `chrome://newtab`? And you're trying to fetch an external resource... Hm. Try creating a [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) instead of using the URL as a string parameter to fetch. Specify the [`.mode`](https://developer.mozilla.org/en-US/docs/Web/API/Request/mode) as `'no-cors'`. In this state, it may not be possible to retrieve the text. You may need to ask this as a different question concerning chrome://newtab specifically. – TylerY86 Oct 06 '16 at 21:41
  • Excellent example. I just made a bare-bones static site handler (didn't want all the overhead of a 'real' SSG) that pulls in .md files using `fetch` and converts them to HTML inside my static HTML pages on the fly. Now I can just `git push` and the site is updated on GitHub pages :-) – Dave Everitt Apr 10 '19 at 17:35
6

Make an AJAX call to the url. Here is using the jQuery library:

$.get( "http: //my.url.com/file.txt", function( data ) {
  var text = data;
});

To extract what you need from your text string in between the paragraph tags, try regex:

var pText = text.match(/<p>([^<]+)<\/p>/)[1];
comixninja
  • 748
  • 6
  • 17
0

Using vanilla JS :

From the MDN doc :

function reqListener () {
  console.log(this.responseText);
}

var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "http://www.example.org/example.txt");
oReq.send();

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

Read the doc and ndcomix SO link to go further (error checking and such)

Community
  • 1
  • 1
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • Since before Febuary of 2015, we've been climbing out of the dark ages. https://davidwalsh.name/fetch https://gauntface.com/blog/2015/02/11/fetch-is-the-new-xhr – TylerY86 Sep 28 '16 at 21:59
  • Disclaimer: Not supported in all browsers. Here's a polyfill. https://github.com/LuvDaSun/xhr-polyfill – TylerY86 Sep 28 '16 at 22:05
-1

Just use jquery. It's easy fun and extensible. Don't try bizzare uses. Be sure all the time to be compatible through all the browser. If you copy this and run it under a local or remote webserver will work like a charm. Cheers.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $.ajax({url: "test.txt", success: function(result){
            $("#div1").html(result);
        }});
    });
});
</script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>

<button>Get External Content</button>

</body>
</html>
MagiciaN
  • 65
  • 9