Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
73
rated 0 times [  76] [ 3]  / answers: 1 / hits: 30865  / 13 Years ago, wed, january 11, 2012, 12:00:00

I've this function



function getTags(level){
$.getJSON(php/get-tags.php, { parent: level }, function(json) {
return json;
});
}


I'm calling this function as



$(function(){
var tags = getTags('0');
});


The problems is, in the function getTags() the return json is like



{tags:[Mathematics,Science,Arts,Engineering,Law,Design]}



but at var tags = getTags('0'), catching the return value, it gets an undefined value.



Is the way I'm returning the value incorrect?


More From » jquery

 Answers
54

Like many others already correctly described, the ajax request runs asynchronous by default. So you need to deal with it in a proper way. What you can do, is to return the jXHR object which is also composed with jQuery promise maker. That could looke like



function getTags(level){
return $.getJSON(php/get-tags.php, { parent: level });
}


and then deal with it like



$(function(){
getTags('0').done(function(json) {
// do something with json
});
});

[#88072] Tuesday, January 10, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
travion

Total Points: 137
Total Questions: 96
Total Answers: 103

Location: India
Member since Wed, Aug 4, 2021
3 Years ago
;