J. Doe J. Doe - 1 year ago 100
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
alert('Problem with request');

return name; //however this is returning null


Answer Source

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);

foo(function (result) {
    var name = result;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download