1

I ran into a roadblock when developing my website. I need it to pull a text file in the same directory and return each line as an array.

So I did my research and came up with a function that seemed simple enough. However when I alert(theArray); it returns as undefined. What am I doing wrong?

function pullText(x)
{
  var fullText = [];
  fileReturn=new XMLHttpRequest();
  fileReturn.onreadystatechange=function()
  {
    if (fileReturn.readyState==4 && fileReturn.status==200)
    {
      entireTextFile = fileReturn.responseText;
      // alert(entireTextFile); works as expected here
      lines = fileReturn.responseText.split("\n");
      // alert(lines); works as expected here
      fullText = lines;
    }
  }
  // alert(fullText); does not work.
  fileReturn.open("GET",x,true);
  fileReturn.send();
  return fullText;
}

1 Answer 1

2

It won't work that way because AJAX is A-synchronous. You should pass a callback handler and call that once the document is ready.

function pullText(x, callback)
{
//      var fullText = []; not necessary
  fileReturn=new XMLHttpRequest();
  fileReturn.onreadystatechange=function()
  {
    if (fileReturn.readyState==4 && fileReturn.status==200)
    {
      entireTextFile = fileReturn.responseText;
      // alert(entireTextFile); works as expected here
      lines = fileReturn.responseText.split("\n");
      // alert(lines); works as expected here
      callback(lines);
    }
  }
  // alert(fullText); does not work.
  fileReturn.open("GET",x,true);
  fileReturn.send();
}

pullText(whatever, function(lines) {
    // use lines here
});
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.