Reputation: 55
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
Reputation: 32912
$.get
is probably jQuery AJAX call, where A stands for Asynchronous. The order of the events is
$.get
is called, waiting for response and call the second parameter function after the response comesvar y = data;
, but the response setting the data haven't been sent yet (the rest of the function (setPoint
is processed, too)data
(too late)There are two workarounds:
$.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
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