0

I'm working on a live update chart, and for that, I made a separate file with the data I need. I made a request on my main page with AJAX so I could get the Array into the main page. But for some reason, I can't use this array outside the request. I would need to use this arrays inside the part only.
Here's what I have:

<script>
    $(document).ready(function(){
      $.getJSON("loadchart.php", function(data){
          var sensor1 = data[0];
          var sensor2 = data[1];
          var sensor3 = data[2];
          var sensorsum = data[3];
      });
    });
    console.log(sensor1);

    //My chart stuff down here

When I try to console log of the array it gives an error:

Uncaught ReferenceError: sensor1 is not defined
    at main.php:107

This is the new function I tried:

async () => {
      async function foo() {
        return $.ajax({
          url: "loadchart.php",
          success: function(data){
            return data;
          }
        });
      }

    var result = await foo();

    console.log(result);
    };
Matheus
  • 83
  • 6
  • Your error is coming from scope issues btw, but the main problem is the link above. – ASDFGerte Nov 12 '19 at 00:24
  • You can not read variable 'sensor1' because this variable is declared later in the scope because ajax response is async and called after reading that variable. Check @ASDFGerte posted link. – daremachine Nov 12 '19 at 00:31
  • @ASDFGerte Isn't a easier solution for only taking it out of the AJAX request? – Matheus Nov 12 '19 at 01:01
  • @ASDFGerte I would have to change my $.getJSON? – Matheus Nov 12 '19 at 01:11
  • @Matheus here is a [jsfiddle](https://jsfiddle.net/21e4kh7t/90/) with some examples of deferred objects using jquery, Hope it helps – stan chacon Nov 13 '19 at 16:52

1 Answers1

0

There are two reasons why sensor1 is undefined.

One reason is that you declare the variable in a lower scope. You can't access a variable that was declared in your callback function outside that callback function.

The second reason is because a callback function gets called after a response is given from the api that you are calling. However, you are trying to access the variable right away when the script runs. This won't work because you need the variable to be defined first.

The solution:

$(document).ready(function(){
    $.getJSON("loadchart.php", function(data){
         var sensor1 = data[0];
         var sensor2 = data[1]; 
         var sensor3 = data[2]; 
         var sensorsum = data[3];

         //move the console.log into this scope.
         console.log(sensor1);
     }); 
}); 

Keep in mind, the console.log() will only work if:

The request is successful

The returned data has the same data structure as you are using.

programmerRaj
  • 1,810
  • 2
  • 9
  • 19