Search code examples
javascriptjqueryajaxflot

Configuring tooltips for Flot charts where data is from an ajax call


I have a series of charts on a page which all get their data from an ajax call. I'm trying to implement the tooltips plugin. I have set grid{ hoverable: true} but I'm still not getting any tooltips.

Code for one of my chart plots...

$(function() {
    var data = [];

    getData();

    function getData() {
        $.ajaxSetup({cache:false});
        $.ajax({
            url:'data/prod.php',
            dataType:'json',
            success:update,
            error: function(){
            }
        });
    }

    function update(ajaxdata) {
        if(ajaxdata){
            $.each(ajaxdata, function(key, value){
                data.push(value);
            });

            if(data.length>0){
                $.plot('#graph-1', [data], {
                    series: {color:"#009390",
                    bars: {
                        show: true,
                        barWidth: 0.5,
                        fill: 0.7,
                        align: "center"
                    },
                    grid: {
                        hoverable: true
                    },
                    tooltip: { //corrected from tooltips to tooltip but issue remains
                        show: true,
                        content: "$s: $x - $y"
                    },
                    legend:{
                        show: false
                    }
                },
                xaxis: {
                    mode: "categories",
                    tickLength: 0,
                    axisLabel: 'Product Categories',
                    axisLabelUseCanvas: true,
                    axisLabelFontSizePixels: 15,
                    axisLabelColour: '#333',
                    axisLabelPadding: 10
                },
                yaxis:{
                    axisLabel: 'Number of Products',
                    axisLabelUseCanvas: true,
                    axisLabelFontSizePixels: 15,
                    axisLabelColour: '#333',
                    axisLabelPadding: 10
                }
            });

            $('#graph-1').css('background','#fff');
            data = [];
        }
    }
}

I've seen some examples that bind to the plothover event but I'm not sure how to implement this into the code above where the plotting is initiated from an ajax call.


Solution

  • Multiple issues:

    1) Options for the tooltip plugin belong under tooltip not tooltips (already fixed in question).

    2) Both grid and tooltip options don't belong under the series options but beside them.

    3) Inside the content format string variables are marked by % not $.

    Fixing all these leads to working tooltips: Fiddle