Travis Bishop
Travis Bishop

Reputation: 25

AJAX/ Javascript - Pass contents of txt file into Javascript variable

I'm trying to read a list of words from a txt file into a Javascript variable to use later in my script. However, I am unable to pass the variable out of the onreadystatechange function. Is there some simple step that I'm missing?

Source:

var xmlhttp;
var list = new Array();
var word;

if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();
else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        list = xmlhttp.responseText.split("\n");
        document.getElementById("testfield").innerHTML = list[0]; //This works
        word = list[0];
    }
}

xmlhttp.open("GET","wordlist.txt",true);
xmlhttp.send();

document.getElementById("testfield").innerHTML = word; //This doesn't work

Upvotes: 1

Views: 981

Answers (1)

Adam Rackis
Adam Rackis

Reputation: 83376

The problem is that this code

document.getElementById("testfield").innerHTML = word; //This doesn't work

is being run before your xhr callback. As a result, word is undefined

This xmlhttp.send(); is sending off your ajax request, and then returning immediately. Your code then proceeds to

document.getElementById("testfield").innerHTML = word;

where word is still undefined, then, some time later, your ajax request completes, your callback is called, and word is set to the result too late for your to care.

Upvotes: 4

Related Questions