-2

My MWE data.js looks like this:

var data = [];
function initdata(){
    $.ajax({
        ...
        success: function(data){
            data.push("test");
        },
        ...
    });
}
$(document).ready(function(){
    initdata();
    console.log(data.length);
    console.log(data[0]);
}

But the console says, data.length is 0 and data[0] is undefined. How can I access data from an ajax function in another function?

LukeLR
  • 1,129
  • 1
  • 14
  • 27

1 Answers1

3

$.ajax() is asynchronous, so by the time it completes its request and runs data.push('test') your console.log(data.length) has already completed.
A way to fix this is to use a callback:

function initdata(callback) {
    $.ajax({
        ...
        success: function(result) { // or just success: callback,
            callback(result);
        }
    });
}
$(document).ready(function() {
    initdata(function(data) {
        console.log(data.length);
        console.log(data[0]);
    });
}
tklg
  • 2,572
  • 2
  • 19
  • 24