Search code examples
javascriptjqueryajaxflot

Plotting realtime with Flot and AJAX - Doesn't plot


I'm trying to plot time data using flot JQuery library, but it simply doesn't.

The objective is to get the data from a JSON file like:

{
"dados": 150
}

The method I'm using is kinda:

function getData() {
        $.ajax({
            type: 'GET',
            url: './data/realtime.json',
            dataType: "json",
            success: function (aferido){
                console.log("Data received. -> var aferido.dados: ", aferido.dados);
                data.push([Date.now(), aferido.dados]); //push something like [timestamp ,value]
                console.log("Data pushed. -> var data: ", data);
                interactive_plot.setData(data);
                interactive_plot.draw();
            }
        });
    }

In console the "data" variable is alright, increasing in every update. Ex:

Data pushed. -> var data: [Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2]]

But the graphic stay static. Any light? I've already tried to change the setData parameter, including array brackets, but the problem persists.


Solution

  • The reason it is static is because that's how flot works - it doesn't automatically move the x-axis when you add new values

    Since you're using time as your y-axis it constantly goes up so you need to change the grid on the fly and make it scroll (auto-advance).

    Examine this simple JSbin

        function getRandomData() {
          res.push([i, Math.random()*50])
          i++;
          return res;
        }
    
    
        function update() {
          plot.setData([getRandomData()]);
    
          //Make the x asis move as i increases
          axes = plot.getAxes();
          axes.xaxis.options.max = i;      //also try Math.max(100,i); //Starts to advance after the graph is filled
          axes.xaxis.options.min = i-100;  //and Math.max(0, i-100); 
    
          plot.setupGrid();
          plot.draw();
    
          setTimeout(update, updateInterval);  
        }
    

    Also, take a look at this example page - ajax and real-time update