Search code examples
jqueryflot

Show date from DB in jQuery flot


I have some data from the Db that I would like to show in a graph. This is data example - date and some number

[[2016-03-10, 4], [2016-03-11, 3], [2016-03-12, 6]]

Data in JS is taken from twig variable

 var searchFlot = '{{ flotSearch|raw }}';
 var barOptions = {
     series: {
         lines: {
             show: true,
             lineWidth: 2,
             fill: true,
             fillColor: {
                 colors: [{
                     opacity: 0.0
                 }, {
                     opacity: 0.0
                 }]
             }
         }
     },
     xaxis: {
         mode: "time",
         timeformat: "%Y-%m-%d",
         minTickSize: [1, "day"]
     },
     colors: ["#1ab394"],
     grid: {
         color: "#999999",
         hoverable: true,
         clickable: true,
         tickColor: "#D4D4D4",
         borderWidth:0
     },
     legend: {
         show: false
     },
     tooltip: true,
     tooltipOpts: {
         content: "x: %x, y: %y"
     }
 };
 $('document').ready(function() {
     $.plot($("#flot-search"), [{label: "Searches", data: searchFlot}], barOptions);
 });

It shows graph grid, but no data plotted on the graph. X-axis shows only 1970-01-01 label.


Solution

  • You need to use timestamp format

    var searchFlot = [[moment("2016-03-10"), 4], [moment("2016-03-11"), 3], [moment("2016-03-12"), 6]];
    

    I used moment() in order to keep your dates

    I added some code of mine because I recently did a very similar project, hope it helps.

    Fiddle here