-3

I have:

var datahere;
var url = "/example.txt"

example.txt has the text "Hello World"

How do I get datahere to equal this string outside of any request?

I'm happy to include PHP into the equations if necessary.

user6227447
  • 51
  • 1
  • 3
  • 2
    Your question is quite vague and unclear. Where is this file, on the local machine or on a server? What does `XMLHttpRequest` have to do with it? Why would you introduce PHP into the mix (is there a server involved)? – T.J. Crowder Jul 22 '16 at 07:57
  • It's on a server. I XMLHttpRequest is what I've been told to use so far, but could get it to work. PHP because it's on a server. – user6227447 Jul 22 '16 at 08:00
  • 1
    Great -- use the "edit" link to add the necessary information to the question. Note that this is a really basic use of `XMLHttpRequest`. You really should read some of the thousands of examples on the web which show exactly how to do this (you don't need PHP). Just any basic `XMLHttpRequest` example will do it. – T.J. Crowder Jul 22 '16 at 08:01

1 Answers1

0

Like @J.T. Crowder said, your question is not very specific about your scenario. You can also find plenty of websites explaining in great detail how XMLHttpRequests work. What you want can be achieved with a simple request like this:

var result, url = "/example.txt";

var xhr = new XMLHttpRequest();
xhr.open("GET",url,true);
xhr.onreadystatechange = function(e) {
    if(xhr.readyState == 4 && xhr.status == 200) {
        result = xhr.responseText;
        document.writeln(result);
    }
};
xhr.send();

This specific script will run under any webserver, but it won't run if you open it locally.

Here's one of those websites that explain everything https://xhr.spec.whatwg.org/

ThijmenDF
  • 117
  • 6