Reputation: 47
I'm using chartjs to display live streaming data from the server i have used ajax with php to get data every second but i think this not the best idea. here is my javascript code.
$(document).ready(function(){
$.getJSON({
url: "http://localhost/chartJS/data.php",
method: "GET",
success: function(data) {
console.log(data);
var player = [];
var score = [];
$.each(data, function(key, value){
player.push("Player "+value[0]);
score.push(parseInt(value[1]));
});
var chartdata = {
labels: player,
datasets : [
{
label: 'Player Score',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: score
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'line',
data: chartdata
});
},
error: function(data) {
console.log(data);
}});
updateChart();
});
function updateChart()
{
var x=2;
$(document).ready(function(){
$.getJSON({
url: "http://localhost/chartJS/data.php?x="+x,
method: "GET",
success: function(data) {
console.log(data);
var player = [];
var score = [];
$.each(data, function(key, value){
player.push("Player "+value[0]);
score.push(value[1]);
});
var chartdata = {
labels: player,
datasets : [
{
label: 'Player Score',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: score
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'line',
data: chartdata,
});
},
error: function(data) {
console.log(data);
}
});
});
setTimeout(function(){updateChart()}, 1000);
}
i've heard about websocket but i don't really know if i should use it or not and if yes how can i get the data continuously every time i open the chart.
Upvotes: 0
Views: 987
Reputation: 2681
I think what you are looking for is interval:
The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds).
Example:
setInterval(function(){ alert("Hello"); }, 3000);
It triggers an alert every 3 seconds.
So in your case, just set an ajax call inside the interval and call it every 1000 miliseconds and then modify the graph with the new data.
Upvotes: 2