1

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.

1
  • You can't alert outside the callback. Commented Jan 11, 2016 at 18:39

1 Answer 1

4

$.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
Sign up to request clarification or add additional context in comments.

1 Comment

Many thanks for the excellent and quick response. That makes total sense, and I was able to get my function to work properly by following your suggestion. Cheers!

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.