I have the following function. When I try to log the varible, it gives me undefined. I think it's because of the loading time from the AJAX GET call, but I don't know how to fix it.
EDIT: Yes, all the values are correct. The console.log logs the correct value, so everything within the function works. It's just the return that does not work.
Any ideas?
function loadOnderhoud() {
var username = window.sessionStorage.getItem("huidigeGebruiker");
var url = "restservices/gebruiker?Q1=" + username;
$.ajax({
url : url,
method : "GET",
beforeSend : function(xhr) {
var token = window.sessionStorage.getItem("sessionToken");
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
},
success : function(data) {
var onderhoud;
$(data).each(function (index) {
if (this.geslacht == "m"){
onderhoud = (66 + (13.7 * this.gewicht) + (5 * (this.lengte*100)) - (6.8 * this.leeftijd)) * this.activiteit;
}
else if (this.geslacht == "v"){
onderhoud = (655 + (9.6 * this.gewicht) + (1.8 * (this.lengte*100)) - (4.7 * this.leeftijd)) * this.activiteit;
}
});
console.log(onderhoud);
return onderhoud;
},
});
}
function loadAdviezen(){
var onderhoud = loadOnderhoud();
}