When working with Ajax to get data, I encountered a situation where I needed to return the value of `username` from within an if statement that is inside a loop and a function. How can I achieve this? Your help would be appreciated.
$.ajax({
dataType: 'json',
url: 'example.com',
type: 'POST',
success: function (data) {
for (var i = 0; i < data.users.length; i++) {
if (user_id == data.users[i].id) {
var username = data.users[i].username;
return username; // <<< This is what I need help with.
};
};
}
})
console.log(username) // The error message says "Username is not defined".