My question is essentially that I am trying to make a universal Ajax function solely for retrieving information which will be parsed and then automatically stored as the value of whatever called it. In this specific case it is a giant dictionary word-list for a hangman game I am making. How can I escape the Array that is created by ajaxRequest.responseText.split("\n") into whatever calls it. In my case it will be ALAMI.Hangman.Wordlist
My end goal is to be able to use ALAMI.Hangman.Wordlist[i] and have it return the value of whatever string is stored at that place in the Array.
Before you freak out this isn’t all of my code the XHR request function is called through ALAMI.XHR(); as written below but I didn’t include it in this code because I felt it was unnecessary.
ALAMI.XHR.Get = function(URL){
"use strict";
var ajaxRequest = ALAMI.XHR();
var ajaxResponse;
ajaxRequest.open("GET", URL, true);
ajaxRequest.send(null);
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState === 4){
ajaxResponse = ajaxRequest.responseText.split("\n");
var extensionLocation = URL.lastIndexOf('.');
console.log(URL.substr(extensionLocation) + " file ...... " + ajaxResponse.length + " lines.");
}
}
return ajaxResponse;
}
ALAMI.Hangman = ALAMI.Hangman || {};
ALAMI.Hangman.Wordlist = ALAMI.XHR.Get('fulldictionary.txt');
//I want ALAMI.Hangman.Wordlist to be equal to the Array of ajaxRequest.responseText.split("\n")
My end goal is to be able to use ALAMI.Hangman.Wordlist[i] and have it return the value of whatever string is stored at that place in the Array.
Also I’m trying to make my ajax function a universal method that I can use an infinite number of times. for example:
ALAMI.Hangman.Wordlist1 = ALAMI.XHR.Get('fulldictionary.txt');
ALAMI.Hangman.Wordlist2 = ALAMI.XHR.Get('dictionary2.txt');
The end goal is:
If in the global space I write console.log(ALAMI.Hangman.Wordlist[0]); it currently shows up as undefined, however, what I want is for the array to have been stored in ALAMI.Hangman.Wordlist so that when I do that it will ouput the first value of the array.
console.log(ALAMI.Hangman.Wordlist[0]); //Should output Apple
Thanks to everyone who helped me answer this question! All the answers given contained usefull relevant information to help answer the question, however, since no one response contained all the understanding I needed to resolve my problem I am posting the answer.
The solution is as follows:
The callback function should only execute after the XHR request had been completed.
-This is especially important and relevant to the fact that we are using asynchronous AJAX.
I needed to make sure that
ALAMI.Hangman.Wordlistwas set as equal to the appropriate valueajaxResponse, and not toALAMI.XHR.Get().The code I came up with is as follows.