Jordan Simon
Jordan Simon

Reputation: 53

Cannot access outside variables from the jquery get function

I am trying to turn csv into associative array but the $.get function does not change the outside textData variable

function csvToArray(filename){

var textData;
var headers = new Array(),
    dataValues = new Array();

$.get(filename, function(data){
    textData = data;
});

var dataArray = textData.split('\n');
headers = dataArray[0].split(',');

for(var i = 1; i<dataArray.length; i++){
    var thisLine = dataArray[i].split(','),
        tempArray = new Array();

    for(var j = 0; j<thisLine.length; j++){
        tempArray[headers[j]] = thisLine[j];
    }

    dataValues.push(tempArray);
}

return dataValues;

}

Why is textData not being set?

Upvotes: 1

Views: 148

Answers (1)

Sushanth --
Sushanth --

Reputation: 55750

get is Async

So by the time textData is set , the remaining statements are already executed.

So consider moving the statements after the get to inside the callback, wherein the textData is populated and then processing can be done on it.

Upvotes: 5

Related Questions