1

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?

gen_Eric
  • 223,194
  • 41
  • 299
  • 337

1 Answers1

5

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.

Sushanth --
  • 55,259
  • 9
  • 66
  • 105
  • can you set async to false or would just making it an ajax call with async:flase be better? – Jordan Simon Jul 11 '13 at 17:59
  • @JordanSimon - Using synchronous requests is a [bad idea according to MDN](http://mdn.beonex.com/en/DOM/XMLHttpRequest/Synchronous_and_Asynchronous_Requests.html): *Note: You shouldn't use synchronous XMLHttpRequests because, due to the inherently asynchronous nature of networking, there are various ways memory and events can leak when using synchronous requests.* (That's in the context of XMLHttpRequests, but the principle still applies since that's probably what jQuery uses under the hood.) – DaoWen Jul 11 '13 at 18:02