Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
38
rated 0 times [  44] [ 6]  / answers: 1 / hits: 35704  / 10 Years ago, wed, july 23, 2014, 12:00:00
function test(){
$.getJSON( notebook-json-data.php, function( data ) {
var myData = data;
});
}


Here in my function i get json objects, but i want to access myData variable from out side the scope of its function.



I have tried setting var myData outside the function but no luck.. :(



I am not familiar with JSON, did i need any parsing?



how to set this variable as global??



Please help...


More From » jquery

 Answers
3

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.


[#70080] Tuesday, July 22, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cherish

Total Points: 734
Total Questions: 94
Total Answers: 86

Location: Senegal
Member since Fri, Aug 21, 2020
4 Years ago
cherish questions
Tue, Jan 25, 22, 00:00, 2 Years ago
Mon, Oct 5, 20, 00:00, 4 Years ago
Mon, Jun 22, 20, 00:00, 4 Years ago
;