0

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?

Community
  • 1
  • 1
jquijano
  • 128
  • 3
  • 12
  • You cannot pass variables into global scope like that because AJAX is asynchronous. The `document.write` like happens *before* the result is returned. http://www.html5rocks.com/en/tutorials/es6/promises/ – Jay Blanchard Apr 28 '16 at 17:52
  • Jay is correct you can however pass the result value upon successful completion of your ajax call. – Edward Apr 28 '16 at 18:01

1 Answers1

0

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.

seanTcoyote
  • 372
  • 3
  • 9