Why is jQuery.getJSON not returning data?

I have this method:

function getUserName(guid) { var name = "Unbekannt"; $.getJSON(urlCurrent, { "method" : "get_user_info", "guid" : guid, "auth_token" : temporaryAuthToken }, function(data) { if (data.status == 0) { alert(data.result[0].name); name = data.result[0].name; } }); return name; } 

Almost everything works: Ajax-Request receives the data and runs the callback function, so

 alert(data.result[0].name); 

shows a popup with this value: "Forename Surname"

But then with

 return name; 

the method returns "Unbekannt", although the name should have a new value "Forename Surname". What happened and where is the mistake?

thanks a lot

+4
source share
3 answers

I return a promise object from a function and act on it.

 function getUserName(guid) { return $.getJSON(urlCurrent, { "method" : "get_user_info", "guid" : guid, "auth_token" : temporaryAuthToken }); } getUserName(guid).done(function(data) { if (data.status == 0) { alert(data.result[0].name); } }); 

And, if you want to do a state check in front, then that's good.

 function getUserName(guid) { return $.getJSON(urlCurrent, { "method" : "get_user_info", "guid" : guid, "auth_token" : temporaryAuthToken }).then(function(data){ return $.Deferred(function(def){ if (data.status == 0) { return def.resolve(data); } return def.reject(data); }); }); } getUserName(guid).done(function(data) { alert(data.result[0].name); }); 
+4
source

When you return name , it has not yet been assigned a new value obtained from the getJSON callback, since the ajax call is asynchronous and takes some time.

Instead, you need to call the callback function:

 function getUserName(guid, callback) { var name = "Unbekannt"; $.getJSON(urlCurrent, { "method" : "coinor.get_user_info", "guid" : guid, "auth_token" : temporaryAuthToken }, function(data) { if (data.status == 0) { alert(data.result[0].name); name = data.result[0].name; callback(name); } }); } getUserName(guid, function(name) { alert(name); }); 
+3
source

Because return name; executes before returning an ajax call.

If you want it to refer to the data that was returned in the $.getJSON() call, it must also be inside the callback function.

+2
source

All Articles