This question already has an answer here:
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?
</div>
As mentioned in the comments, it's not a hoisting issue, the issue is that you're trying to use result
before the XHR call has returned data. You can get your current code to work, simply by moving the reference to result
inside of the oReq.onload
callback:
var result;
var oReq = new XMLHttpRequest();
oReq.onload = function getData() {
result = this.responseText;
console.log(result);
};
oReq.open("get", "data.php", true);
oReq.send();
Then just update whatever part of your app needs the data there, instead of logging it to the console.