J. Doe J. Doe - 1 month ago 15
Javascript Question

Javascript function returning null

I wrote a function that is getting some data from a php file. When I parse it and use an alert box to show it, it works fine but when I try to return the value it comes as undefined. I have no idea why this happening

function getUser(){
var httpRequest = new createAjaxRequestObject();
httpRequest.open('GET', 'getUser.php', true);
var name;
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200){
name = JSON.parse(httpRequest.responseText);
alert(name); //this works just fine and display the name john
}
else{
alert('Problem with request');
}
}

}
httpRequest.send();
return name; //however this is returning null

}

Answer

Right now it sends null , because it takes the value as soon as httpRequest.send(); is called.

In this case you need to pass a callback to function that will receive the return value

Change like this,

function foo(callback) {
    httpRequest = new XMLHttpRequest();
    httpRequest.onreadystatechange = function () {
        if (httpRequest.readyState === 4) { // request is done
            if (httpRequest.status === 200) { // successfully
                callback(httpRequest.responseText); // we're calling our method


            }
        }
    };
   httpRequest.open('GET', 'getUser.php', true);
    httpRequest.send();
}

foo(function (result) {
    var name = result;
});