0

I am trying to draw some data with Flot, retrieving the data from a API in JSON format.

    $.getJSON(jsonURL, function(result){            
        $.each(result, function(key, val){
            var fecha = parseFloat(new Date(val.fecha).getTime());
            var temp= parseFloat(val.tempsensada1);
            d1.push([fecha,temp]);          
        });
    });
    var data1 = [{ data: d1, label: "d1" }];
    var options = {
    canvas: false,
    xaxes: [
        { mode: "time" }
    ],
    yaxes: [
        { min: 0 }          
    ],
    legend: { position: "sw" }
};
$.plot("#box-four-content", data1,options);

The problem is that there is no line drawn. But when I populate my d1 with some dummy data and without parsing the JSON like this:

d1.push([new Date("2018-02-10 08:00:00").getTime(), parseFloat("3.8")]);
d1.push([new Date("2018-02-11 09:00:00").getTime(), parseFloat("8")]);
d1.push([new Date("2018-02-12 10:00:00").getTime(), parseFloat("10")]);
d1.push([new Date("2018-02-12 10:10:00").getTime(), parseFloat("4")]);
d1.push([1520344993000, 18]);

It works like a charm. What am I missing here?

gre_gor
  • 6,669
  • 9
  • 47
  • 52

1 Answers1

0

The $.getJSON() function is asynchronous, which means the d1 array is filled with the data after the request finishes. But the rest of your code executes instantly after the request is started when the d1 is still empty. (See this answer for more information.)

To fix your code you have to put all the code for the chart into the callback function, like this:

$.getJSON(jsonURL, function(result){            
    $.each(result, function(key, val){
        var fecha = parseFloat(new Date(val.fecha).getTime());
        var temp= parseFloat(val.tempsensada1);
        d1.push([fecha,temp]);          
    });
    var data1 = [{ data: d1, label: "d1" }];
    var options = {
        canvas: false,
        xaxes: [
            { mode: "time" }
        ],
        yaxes: [
            { min: 0 }          
        ],
        legend: { position: "sw" }
    };
    $.plot("#box-four-content", data1,options);
});
Raidri
  • 17,258
  • 9
  • 62
  • 65