1

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

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.