user5064798
user5064798

Reputation:

JavaScript var outside function

How do I retrieve returndata variable outside fn() function?

function fn() {
    var xmlhttp = new XMLHttpRequest();
    var vars = "request=something";

    xmlhttp.open("POST", "script.php", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    xmlhttp.onreadystatechange = function() {
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var returndata = xmlhttp.responseText;
        }
    }

    xmlhttp.send(vars);
}

Upvotes: 0

Views: 551

Answers (2)

Mouser
Mouser

Reputation: 13304

AJAX requests are asynchronous. You cannot have the pizza before it is baked. In real life you call the pizza company. They bake it and you wait. AJAX is the same. So setting the returndata won't do it all by itself.

function fn() {
    var xmlhttp = new XMLHttpRequest();
    var vars = "request=something";

    xmlhttp.open("POST", "script.php", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    xmlhttp.onreadystatechange = function() {
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var returndata = xmlhttp.responseText;
        }
    }

    xmlhttp.send(vars);
}       

The readystate function isn't there for nothing. It waits until the request has been processed. From there on you can go on. Every function/script that is depended on the returned data should be called upon from that function.

Still you can do this:

    var returndata; //this will now be a global variable.
function fn() {
    var xmlhttp = new XMLHttpRequest();
    var vars = "request=something";

    xmlhttp.open("POST", "script.php", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    xmlhttp.onreadystatechange = function() {
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var returndata = xmlhttp.responseText;
            doSomeThing(); //fire depended value.
        }
    }

    xmlhttp.send(vars);
}

function doSomething()
{
    if(returndata)
    {
         //do Something
    }
    else
    {
        alert("Data isn't loaded yet");
    }
}       

Upvotes: 1

Jakuje
Jakuje

Reputation: 26016

You need to define global variable before function and then store the result into this variable. The way you do it now, is definition of local variable.

var returndata;
function fn() {
    var xmlhttp = new XMLHttpRequest();
    var vars = "request=something";

    xmlhttp.open("POST", "script.php", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    xmlhttp.onreadystatechange = function() {
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            returndata = xmlhttp.responseText;
        }
    }

    xmlhttp.send(vars);
}

Upvotes: 2

Related Questions