-1

Here's the rundown. I have an external .txt file which has a number of locations (one per line) which I need to have loaded into my script to populate a dropdown. I'm using .get() to pull in the data, and putting it into an array. It LOOKS correct, but the dropdown isn't populated. Doing some tests, I found if I manually populate the array when I declare it the data I declare there loads fine. Also, if I try doing anything to the array such as turning it into a string nothing happens, and if I try checking the length it reports 0. I've tried making a new array and pushing the content of the first into it, but no dice. I've also tried using makeArray, but that didn't work.

Here's my code so far:

var siteIdArray = [];
var path = "*snipped*/siteId.text";
var option = "";

$.get(path, function(data)
{
  siteIdArray = data.split("\n");
  console.log(siteIdArray);
});

for (i = 0; i < siteIdArray.length; i++)
{
  option += '<option value="'+ siteIdArray[i] + '">' + siteIdArray[i] + '</option>';
}
$('#siteId').append(option);

Here's a test of what my siteIdAarray contains (full array has a total of 62 items):

["AN", "AZ", "BA", "CA"]

And the siteId.txt looks like this:

AN
AZ
BA
CA

2 Answers2

1

$.get is an async call, you have to do all the work with the response object inside the callback or pass it to another function:

$.get(path, function(data)
{
  siteIdArray = data.split("\n");
  console.log(siteIdArray);

  for (i = 0; i < siteIdArray.length; i++)
  {
      option += '<option value="'+ siteIdArray[i] + '">' + siteIdArray[i] + '</option>';
  }
  $('#siteId').append(option);
});
tymeJV
  • 103,943
  • 14
  • 161
  • 157
1

$.get is asynchronous, so all the code dependant on siteIdArray needs to be in the callback function.

What's happening is your code is reaching the for loop but at that stage sideIdArray has not yet been populated by the AJAX response, which is why your call to console.log works but the rest does not.

Your code updated:

var siteIdArray = [];
var path = "*snipped*/siteId.text";
var option = "";

$.get(path, function(data)
{
  siteIdArray = data.split("\n");
  console.log(siteIdArray);

  for (i = 0; i < siteIdArray.length; i++)
  {
    option += '<option value="'+ siteIdArray[i] + '">' + siteIdArray[i] + '</option>';
  }

  $('#siteId').append(option);
});
Community
  • 1
  • 1
bcmcfc
  • 25,966
  • 29
  • 109
  • 181