Don't try to set myData as a global variable - it won't work because getJSON is asynchronous. Either use a promise:
function test() {
return $.getJSON('notebook-json-data.php');
}
$.when(test()).then(function (data) {
console.log(data);
});
Or a callback:
function test(callback) {
$.getJSON('notebook-json-data.php', function (data) {
callback(data);
});
}
test(function (data) {
console.log(data);
});
Edit
Since you want to use the data in other areas of your code, use a closure to create an environment where your variables don't leak out into the global space. For example, with the callback:
(function () {
var myData;
function test(callback) {
$.getJSON('notebook-json-data.php', function (data) {
callback(data);
});
}
test(function (data) {
myData = data;
autoPopulate('field', 'id');
});
function autoPopulate(field, id) {
console.log(myData);
}
});
myData is cached as a global variable specific to that closure. Note the other functions will only be able to use that variable once the callback has completed.
var myDataoutside the function, no repetition ofvarinside the function (this would create a new shadowedmyVar). Bear in mind the call is asynchronous so you can't simply access it after thegetJSONcalltest()instead