# Using JavaScript/JQuery to get words from a text file

1. May 5, 2014

### Jamin2112

I was searching around the internet for a procedure to read lines of a text file into a JavaScript array. Most of the procedures I saw used Ajax, which I don't understand yet, so I'll refrain from trying to cut-and-paste code that I don't understand.

I found this

Code (Text):

$.get('wordsEn.txt', function(myContentFile) { words = myContentFile.split("\r\n"); }, 'text'); JQuery function call, which does the trick, but how can I get words into the scope outside of the function call? I want to actually be able to use it. 2. May 5, 2014 ### Superposed_Cat 3. May 5, 2014 ### .Scott You can declare "var words" before the .get call - but I think that's only half the problem. I haven't used jQuery, but I suspect that "myContentFile" becomes available asynchronously to the rest of the program. So let's say you put the "var words;" and "$.get(..." in the <head> section and a reference to the words array "later" in the body. What will happen is that the reference in the body will happen before the data is ready - that is, before the "function(myContentFile)" is called.

Unless you're already using the jQuery library, I would used code such as this:
Code (Text):
<html>
<script type="text/javascript">
var Words;
var WordFile = new XMLHttpRequest();
WordFile.open("GET", "file:///C:/temp/html/words.txt", false);
function () {
{
if(WordFile.status === 200 || WordFile.status == 0)
{
Words = WordFile.responseText.split("\r\n");
}
}
};
WordFile.send(null);
</script>
<body>
<script type="text/javascript">
document.write(Words[2]);
</script>
</body>
</html>

4. May 8, 2014

### Jamin2112

Seems to work. Thanks.