使用日期范围选择器更新图表JS

时间:2017-12-03 23:17:07

标签: javascript php ajax chart.js

我正在尝试根据使用ajax选择的日期和班次来更新图表。我的ajax调用返回一个这样的数组:

0   
date    "2017-11-20"
shift   "Day Shift"
availability    100
1   
date    "2017-11-21"
shift   "Day Shift"
availability    63.63636363636363
2   
date    "2017-11-22"
shift   "Day Shift"
availability    63.63636363636363
3   
date    "2017-11-23"
shift   "Day Shift"
availability    63.63636363636363
4   
date    "2017-11-24"
shift   "Day Shift"
availability    14.285714285714285
5   
date    "2017-11-20"
shift   "Night Shift"
availability    67.56756756756756
6   
date    "2017-11-21"
shift   "Night Shift"
availability    67.56756756756756
7   
date    "2017-11-22"
shift   "Night Shift"
availability    67.56756756756756
8   
date    "2017-11-23"
shift   "Night Shift"
availability    67.56756756756756

我的javascript看起来像这样:

// on change event
var request;
$('input').on('change', function(event) {
    console.log('changed');
    event.preventDefault();

    // Abort any pending request
    if (request) {
        request.abort();
    }

    var rangeStart = moment($('#daterange').data('daterangepicker').startDate).unix();
    var rangeEnd = moment($('#daterange').data('daterangepicker').endDate).unix();
    var shift = 'all';
    request = $.ajax({
        url: "report_availability.php",
        type: "post",
        data: {
            rangeStart: rangeStart,
            rangeEnd: rangeEnd,
            shift: shift
        }
    });

    request.done(function (response, textStatus){
        drawChart(response); 
    });

    request.fail(function (textStatus, errorThrown){
        // Log the error to the console
        console.error(
            "The following error occurred: "+
            textStatus, errorThrown
        );
    });

    request.always(function () {
       console.log('request finished');
    });
});

function drawChart(data) {
    var dates = [];
    var shift1Score = [];
    var shift2Score = [];
    for(var i in data) {
        var found = jQuery.inArray(data[i].date, dates);
        if (found < 0) {
            dates.push(data[i].date);
        }
         if(data[i].shift == 'Day Shift' ) {
            shift1Score.push(data[i].availability);
        } else {
            shift2Score.push(data[i].availability);
        }
     }

    // Destroy the chart if it already exists
    // NOT WORKING
    if(myChart!=null){
        myChart.destroy();
        console.log('destroy');
    }

    var ctx = document.getElementById("myChart").getContext('2d');
    ctx.canvas.height = 50;
    var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: dates,
            datasets: [
            {
                label: "Day Shift",
                backgroundColor: "#3e95cd",
                data: shift1Score
            }, {
                label: "Night Shift",
                backgroundColor: "#8e5ea2",
                data: shift2Score
            }
          ]
        },
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero:true
                    }
                }]
            },
            responsive: true,
            maintainAspectRatio: false
        }
    });
 }

我有两个问题:

问题1:图表没有被破坏,因此当我重绘它时,它只是在旧图表的顶部重绘,这会导致悬停事件出现问题。我曾尝试使用chart.update()来解决此问题,但这似乎只是添加到原始数据而不是替换它。

编辑: - 我通过删除画布然后创建一个新画布解决了问题1: -

$('#myChart').remove();
$('#chartBar').append('<canvas id="myChart"></canvas>');

问题2:有两个以上的班次......有时甚至高达5,我不想硬编码所有这些。我想根据数组中返回的移位数来绘制每个数据集,我愿意改变php或javascript中的数组结构,但似乎无法找出正确的数组结构或如何构建动态数据集数组图表。

图表应该像这样输出2个班次: enter image description here

任何帮助都会非常感谢

1 个答案:

答案 0 :(得分:2)

我遇到了同样的问题。

为了更新图表,我使用了两个函数:

删除当前图表中的所有数据集:

function removeDataset(chart) {
   chart.data.datasets = [];
};

向图表添加新数据集:

function addDataset(chart, name, data, background, border, fill) {
    var newDataset = {
        label: name,
        data: [],
        backgroundColor: background,
        borderColor: border,
        fill: fill
    };
    for (var index = 0; index < data.length; ++index) {
        newDataset.data.push(data[index]);
    }
    chart.data.datasets.push(newDataset);
};

所以,当我完成ajax时,我会这样使用:

removeDataset(ctx1);
addDataset(ctx1, "Dataset Name", resp.dataset_data_json, "#007bff", "#007bff", true);  
ctx1.update();

要声明图表,我使用:

var ctx1;
$(document).ready(function () {
    var canvas1 = $("#canvas1")[0];   
    canvas1.height = "300";             
    ctx1 = new Chart(canvas1, config_ctx1);
});

我希望它有所帮助。