-3

I am using Ajax to run a PHP script within my site. I would like to set a JS variable to the response from the PHP script.

This script should make the variable "stopAt" set to 42.

Here is my error: Error

Here is my code:

            function reqListener () {
            console.log(this.responseText);
            }

            var oReq = new XMLHttpRequest(); //New request object
            oReq.onload = function() {
                var stopAt = (this.responseText)
            };
            oReq.open("get", "gennum.php", true);                               
            oReq.send();
            theWheel.animation.stopAngle = stopAt;

Here is gennum.php:

<?php
echo json_encode(42);
?>

Thanks! Hopefully you guys can solve my problem! :)

Niyoko
  • 7,512
  • 4
  • 32
  • 59
Jake
  • 13
  • 4

1 Answers1

0

stopAt is a local variable. It is only defined inside the function. You need to move statement that use it into the function.

oReq.onload = function() {
    var stopAt = (this.responseText);
    theWheel.animation.stopAngle = stopAt;
};
Niyoko
  • 7,512
  • 4
  • 32
  • 59
  • Is there any way I can do this by using a global variable... or something? – Jake Nov 11 '16 at 01:54
  • You will still need to set `stopAngle` inside the function. [`XMLHttpRequest.send`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send) is asyncronous, so it will return as soon as possible without waiting request to complete, and the variable will still not defined below `send()` call. – Niyoko Nov 11 '16 at 01:57
  • @jake.......... – Niyoko Nov 11 '16 at 02:03
  • I got it to work! Thank you so much for your help! You are a great part of this community! :) – Jake Nov 11 '16 at 21:03