I have the following code from a question (How to pass variables and data from PHP to JavaScript?):
<!-- snip -->
<script>
function reqListener () {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest(); //New request object
oReq.onload = function() {
//This is where you handle what to do with the response.
//The actual data is found on this.responseText
alert(this.responseText); //Will alert: 42
};
oReq.open("get", "get-data.php", true);
// ^ Don't block the rest of the execution.
// Don't wait until the request finishes to
// continue.
oReq.send();
</script>
<!-- snip -->
What I need is to pass this.responseText
into a global variable named "result" like this:
<script>
var result;
var oReq = new XMLHttpRequest();
oReq.onload = function getData() {
result = this.responseText;
};
oReq.open("get", "data.php", true);
oReq.send();
document.write(result);
</script>
The code does get the data from data.php, however I get a "hoisting" issue, any idea on how to make pass that result into a global variable?