Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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".

like image 413
Roy Justin Avatar asked Jan 03 '14 22:01

Roy Justin


1 Answers

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!

like image 82
tymeJV Avatar answered Oct 16 '22 02:10

tymeJV