0

I have a local text file wordsEn.txt that is all words in the dictionary (lowercased):

a
aah
aahed
aahing
aahs
aardvark
[etcetera]

On page load, I would like those to be placed into an array:

words = ["a", "aah", "aahed", "aaching", "aahs", "aardvark", ...];

Here's the function I made to return the response code when trying to read the text file:

    function get_words()
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("POST", "wordsEn.txt", true);
        rawFile.onreadystatechange = function ()
        {
            if (rawFile.readyState === 4)
            {
                if (rawFile.status === 200 || rawFile.status == 0)
                {
                    return rawFile.responseText;
                }
            }

        }
        rawFile.send(null);
    }

I was trying to copy the procedure here: Javascript - read local text file

(I confess that I copied it without really understanding what it does.)

Apparently it's not working, because

    var resp = get_words(); 
    document.getElementById("spresdiv").innerHTML += "<p>" + resp + "</p>";

writes undefined inside the spresdiv div. Any idea why this is and how I can fix it?

On a related note, does anyone know if JavaScript arrays are implemented with a tree or any other type of fast-lookup? Does indexOf(...) use a linear search?

Community
  • 1
  • 1
  • your confession made my day (y) – Ejaz May 05 '14 at 19:10
  • `return rawFile.responseText;` is where your problem begins. it isn't very meaningful to return from that function, it doesn't do anything. `get_words` has returned `undefined` long before that line gets executed. Don't code with the expectation that you can return the words from `get_words`. – Kevin B May 05 '14 at 19:11
  • Are you sure the AJAX request is working? And actually returning the contents of `wordsEn.txt`? – Amy May 05 '14 at 19:12

1 Answers1

1

Ajax is Asynchronous. you can't return the responseText from get_words. You should instead use callbacks.

function get_words(callback) {
    var rawFile = new XMLHttpRequest();
    rawFile.open("POST", "wordsEn.txt", true);
    rawFile.onreadystatechange = function () {
        if (rawFile.readyState === 4) {
            if (rawFile.status === 200 || rawFile.status == 0) {
                callback(rawFile.responseText);
            }
        }

    }
    rawFile.send(null);
}

get_words(function (resp) {
    document.getElementById("spresdiv").innerHTML += "<p>" + resp + "</p>";
});
Kevin B
  • 94,570
  • 16
  • 163
  • 180