-1

I'm trying to use this function to return as a global variable a String object that is the contents of a local text file. Right now it is returning an empty String.

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

    }
    rawFile.send(null);
    return allText;
}

However, when I change the body of the second if statement to

allText = rawFile.responseText;
alert(allText);

I do get an alert message that is the correct contents of the text file.

However, when I instead put the alert message right before the return statement, I get an empty alert message.

I would be happy if you could give me some insight on the behavior here and possibly help me fix it to accomplish the task of returning as a string the contents of the text file. Thanks in advance.

user3537336
  • 221
  • 2
  • 9
  • This is because the ajax call takes some time to complete, it's running asynchronous. Within the 2nd `if`, you're within the `onreadystatechange` function, which is called multiple times for various statuses. One of them (`200`) will carry your data and alert it properly. – KrekkieD Apr 23 '14 at 17:41
  • this one too : http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – Denys Séguret Apr 23 '14 at 17:42
  • 1
    Please people, vote to close instead of rushing to give a bad one or three lines answer... – Denys Séguret Apr 23 '14 at 17:44

1 Answers1

1

Your code is executing asyncrhonously.

Basically this means that the anonymous function attached to onreadystatechange will only execute upon receipt of the data. So, when your alert is inside of this function (below the allText = rawFile.responseText) the variable allText will contain your file contents (as it's had a chance to be populated).

If, however, you put the alert above the return statement the allText variable is not yet populated and the function returns before the file contents are received.

One way you could overcome this, is by passing a callback function to get_words.

Julio
  • 2,261
  • 4
  • 30
  • 56