0

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();
}
Some Name
  • 561
  • 6
  • 18

1 Answers1

1

Issue is related to return from success function of ajax,

Proper way of doing is Provide the call back function:

function loadOnderhoud(getData) {  
    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);
                getData(onderhoud);
            },
        });
}

function getData(data)
{
    var onderhoud = data;
}
loadOnderhoud(getData);
Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122