i write some function, and i called abApi.general.getUserById function, but when i print output to $("#friend-requests-block") my name variable is empty. i know this is javascript and i try with $("#friend-requests-block") in getUserById callback, but then i haven’t type. How can i fix this?
for (var index in requests) {
var name = "";
var type = "";
if(requests[index].FriendRequestTypeId == 1) {
type = "private";
}
else {
type = "business";
}
abApi.general.getUserById(abEnvironment.sessionToken, requests[index].FromUserId, function(response2){
name = response2.Name;
});
$("#friend-requests-blocks").html($("#friend-requests-blocks").html() + "<div class=\"log-block\" id=\"friend-requests-log-"+requests[index].Id+"\"><a href=\"#\"><h2>"+ name + "("+ type +")</h2></a> <div class=\"friend-requests-buttons\" style=\"margin-top: 15px;\"> <a href=\"javascript:void(0)\" data-role=\"button\" style=\"margin: 0px 5px 0px 5px;\" onClick=\"abAction.approveFriendRequest("+requests[index].Id+", 1,"+requests[index].FromUserId+");\">Accept</a><a href=\"javascript:void(0)\"data-role=\"button\" style=\"margin: 0px 5px 0px 5px;\" onClick=\"abAction.approveFriendRequest("+requests[index].Id+", 0,"+requests[index].FromUserId+");\">Reject</a> <a class=\"button3\" href=\"javascript:void(0)\"data-role=\"button\" style=\"margin: 0px 5px 0px 5px;\" onClick=\"abAction.approveFriendRequest("+requests[index].Id+", 2,"+requests[index].FromUserId+");\">Later</a></div></div>");
}
It’s not just a scope issue you’re dealing with, but the fact that
getUserByIdis async, too (even more than the scope). the variablenamewon’t be set until your script receives a response. Having said that, since you’re using a loop, moving the$('#friend-request-blocks').html()bit to the success callback won’t cut it: the variablesnameandtypewill be reassigned on every loop iteration. To get around this, you’ll have to use a closure:Also, I get the impression you’re looping through an array, not an object, though I could be wrong. If
requestsis an array, it’s best not to use afor...inloop, but a regularfor(var i;i<requests.length;i++)loop. Google will give you a huge list of reasons as to whyfor...inon arrays isn’t the best of ideas.