0

I want to plot with chart.js using json data I query with getjson.

The code below gives me and empty plot. However if I uncomment the line with alert(ddata.length); not only it pops up with a 0 but the plot comes up correctly this time - confusing behaviour. Using chart.js 2.6.0 jquery 3.3.1.

var ddata = [];
//var labels = [];

$.getJSON("http://192.168.1.143/json_request", function(jdata){
    $.each(jdata, function(i, d){
        ddata.push({"x":d.timestamp, "y": d.x0});
        //labels.push(String(d.timestamp));
    });
});

//alert(ddata.length); // <-- Works if uncommented !!!
//console.table(ddata);

var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        //labels: labels,
        datasets: [{
            label: 'h1px2',
            data: ddata,
            backgroundColor: 'rgba(0, 0, 255, 0.2)',
            borderColor: 'rgba(0,0,255,1)',
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            xAxes: [{
                type: 'linear'
            }]
        }
    }
});

A sample of the json:

[{"timestamp": 1528828783,"x0": 246.21,"x1": 1.16,"x2": 11.47,"x3": 8.62,"x4": -127.00},
{"timestamp": 1528828793,"x0": 245.75,"x1": 1.37,"x2": 15.41,"x3": 4.93,"x4": -127.00}, etc...

Would you be able to tell how I can get this plotted correctly?

Noel
  • 3,749
  • 3
  • 22
  • 21
  • 2
    Build your chart inside the `getJSON` callback instead of before the callback runs. – Paul Jun 12 '18 at 19:14
  • do you get any errors in console? – blurfus Jun 12 '18 at 19:14
  • No errors in the console no. Looks like I'll have to work with setTimeout by the look of it. If someone has an example for my case. – Noel Jun 12 '18 at 19:22
  • 1
    You shouldn't use a timer. Right now you're trying to build your chart before you have populated anything in `ddata`. It would be just as incorrect to use a timer and guess whether or not you've populated `ddata` after a certain amount of time. Instead just build the chart right after you know you've populated it. – Paul Jun 12 '18 at 19:30
  • You can put all your code for building the chart inside the `getJSON` callback where you know you've populated `ddata` and don't need to guess. You can also just call another function from there. EG. after your `$.each` loop call a function like `build_chart( ddata );`, and put your other code inside a function `function build_chart( ddata ) { var ctx = ... }` – Paul Jun 12 '18 at 19:33
  • You don't even need to declare `ddata` in an outer scope. You could just put `var ddata = [];` inside your getJSON callback as the first line before `$.each`. – Paul Jun 12 '18 at 19:35

0 Answers0