Access json data outside of $.getJSON()

$(document).ready(function () {
    var value = getParmsVals()["search"];
    $.getJSON('/api/search/GetQuestionByKey/' + value, function (jsonData) {
        $(jsonData).each(function (i, item) {
            var name = getAuthorName(item.userId);
        });
    });
});

function getAuthorName(userId) {
    var fullname = "default";
    $.getJSON('/api/search/GetUserById/' + userId, function (jsonData) {
        fullname = jsonData.firstname + " " + jsonData.lastname;
    });
    return fullname;
}

I’m trying to access the fullname variable by calling the getAuthorName method but I couldn’t get the correct value. It’s always giving me the value “default”.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You wouldn’t return from an async method, as you can see, it doesn’t work! What you need is a callback function, consider:

function getAuthorName(userId, callback) {
    var fullname = "default";
    $.getJSON('/api/search/GetUserById/' + userId, function (jsonData) {
        fullname = jsonData.firstname + " " + jsonData.lastname;
        callback(fullname);
    });
}

Notice how we pass in callback and then call it at the end of your get call? Now call this method like so:

getAuthorName(userID, function(name) {
    console.log(name);
});

And now you have access to fullname in that callback function!

Method 2

I like the answer by @tymeJV it is an easy solve to the problem

I just wanted to point out that solving the big picture of having easily accessible data inside Javascript is a great reason why data-centric JS frameworks exist

http://knockoutjs.com/
http://backbonejs.org/
http://angularjs.org/

Method 3

You can also put your variable on the object and use .bind(), like so:

this.fullname = "default";

$.getJSON('/api/search/GetUserById/' + userId, function (jsonData) {
   this.fullname = jsonData.firstname + " " + jsonData.lastname;
}.bind(this));


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x