Falcon
Falcon

Reputation: 55

Javascript highchart passing a variable

I used the $.get to get the value generated in test2.php, when I do an alert(data) I get the exact value I want, but I don't know what to do to stock the value obtained in the variable y :

   var series = this.series[0];  
   setInterval(function() {

      $.get('test2.php', function(data) {
         alert(data);
      });

      var y = data;  // NOT WORKING !
      var x = (new Date()).getTime();     

      series.addPoint([x, y], true, true);
    }, 1000);

I'm new to JavaScript, so thanks in advance..!

Upvotes: 2

Views: 665

Answers (2)

Jan Turoň
Jan Turoň

Reputation: 32912

$.get is probably jQuery AJAX call, where A stands for Asynchronous. The order of the events is

  1. $.get is called, waiting for response and call the second parameter function after the response comes
  2. var y = data;, but the response setting the data haven't been sent yet (the rest of the function (setPoint is processed, too)
  3. the response comes from server and sets data (too late)

There are two workarounds:

  • either put the code into the $.get function in the second parameter (as Kevin Bowersocks suggests)
  • or do a synchronous call. jQuery won't help you here and I can't recommend it: the browser freezes until the response and if the response is lost, page needs to be reloaded.

    var xhr = new XMLHttpRequest();
    xhr.open("GET","test2.php",false); // false = synchronous call
    xhr.send(); // browser freezes until the response, let's hope not for long
    var y = xhr.response; // response is ready here for synchronous calls
    

Upvotes: 1

Kevin Bowersox
Kevin Bowersox

Reputation: 94489

Javascript uses function scope and Ajax is asynchronous, data is not in scope in the code you execute after the Ajax call. Placing the var y = data; and subsequent code outside the callback causes it to execute before the response from the server is received.

Adding this code inside the callback will cause it to execute once a response from the server is received and when data actually contains the response.

   var series = this.series[0];  
   setInterval(function() {

      $.get('test2.php', function(data) {
         alert(data);
         var y = parseInt(data);  // NOT WORKING !
         var x = (new Date()).getTime();     

         series.addPoint([x, y], true, true);
      });

    }, 1000);

Upvotes: 2

Related Questions