Byron
Byron

Reputation: 27

Reading file with Javascript into array - can't seem to make it work

I have a simple 2-column csv file that I would like my site to read and ultimately parse into an array. The data is in the following format:

Atlanta Braves, Atlanta_Braves
Baltimore Orioles, Baltimore_Orioles
Boston Red Sox, Boston_Red_Sox
etc.

The file is currently stored in the same location as my html file. I am trying to use an ajax request to pull the data from the file into an array, then parse further such that myArray[0][0] = 'Atlanta Braves'.

Here is my code:

var myArray = [];

$.ajax({
    type: 'GET',
    url: 'datafilename.csv',
    success: function(data){processData(data);}
});

function processData(data){
    myArray = data.split('\n');
    for (i = 0; i < myArray.length; i++){
        myArray[i] = myArray[i].split(',');
    }       
}

alert(myArray[0][0]);

Unfortunately, the alert only returns 'undefined'. What am I doing wrong here? Any feedback would be appreciated.

Upvotes: 1

Views: 54

Answers (1)

Mike Cluck
Mike Cluck

Reputation: 32511

$.ajax is an asynchronous function. That means that it won't complete until sometime later, after your other synchronous code has already run. Try adding this:

function processData(data) {
    // Your existing code goes here...
    alert(myArray[0][0]);
}

This works because processData is only run after the AJAX call has returned. Asynchronous functions basically work like this:

var value = 1;
setTimeout(function() {
  value = 2; // This won't happen for about 1 second
  console.log(value); // 2
}, 1000); // Run this function in 1 second
console.log(value); // 1. This happens almost immediately, without pause

Upvotes: 4

Related Questions