0

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 
}
Phil Ross
  • 25,590
  • 9
  • 67
  • 77
J. Doe
  • 63
  • 9
  • Ajax is asynchronous - you're returning the name variable but the Ajax request is not yet finished setting it up. – James A Nov 06 '16 at 05:36

1 Answers1

3

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;
});
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396