I'm getting every 4 secs a json data like this:
{
"time": "04:49:07 AM",
"milliseconds_since_epoch": 1375246147254,
"date": "07-31-2013"
}
I'm processing it in order to get a array like this:
[[1375230673948, 0.6443498175195954]]
(The first data is a js timestamp)
I'm trying to plot these data, on real time using flot:
function draw() {
console.log('draw called');
this.array = getTimeArray();
$.plot(
$("#placeholder"), [
{
label: "test Data",
data: this.array,
lines: {
show: true,
fill: true,
fillColor: "rgba(249, 28, 61,0.3)",
lineWidth: 2.5
},
}
], {
xaxis: {
mode: "time",
timeformat: "%H:%M"
},
yaxis: {
min: -2
}
});
}
function getTimeArray(flg) {
var array = [],
d = new Date(),
tz = d.getTimezoneOffset();
jsonUrl = 'http://date.jsontest.com/'
var array2 = []
$.getJSON(jsonUrl, function(data) {
var i = 0;
$.each(data, function(key, val) {
if (typeof val === 'number'){
d = new Date(val - 5 * 60 * 1000);
array2.push([d.getTime()- tz*60*1000,Math.random()]);
console.log(array2)
i++;
}
});
});
for (var i = 9; i >= 0; i--) {
d = new Date(d.getTime() - 5 * 60 * 1000);
array.push([d.getTime() - tz*60*1000, Math.random()]);
}
return array;
}
draw();
setInterval(draw, 4000);
But I can't get it yet, please could somebody help me?
I need plot the time series with their values getting the data from json.Maybe using another lib it could be reached more easily, any help are welcome..
The problem with your code is that the
$.getJSON
call is asynchronous, so if you try to returnarray2
(in the jsFiddle), it is an empty list. You need to use either thesuccess
callback or the.done()
method to draw the plot, after getting JSON data from the server:You can see the full jsFiddle. I keep pushing to the array and shift it when its length gets above 9, just to illustrate.
You can also use the
setData
anddraw
methods of the flot plot to avoid drawing the plot every time, but that's a different issue.