[Chartjs]-Chart JS Dynamic number of datasets

2👍

Following Matt2’s suggestion I ended up with this solution.

This is the working script:

function LoadProjectActivityGraph(ProjectRef, StartDate, EndDate)
{
var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function()
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
        document.getElementById("ProjectActivityGraph").innerHTML = xmlhttp.responseText;

        //GET THE VALUE OF THE GRAPH LABELS FORM INPUT
        var GraphLabelString = document.forms.GraphData.GraphLabels.value;

        //TURN THE VALUE OF THE ABOVE INTO AN ARRAY
        var GraphLabelArray = GraphLabelString.split(","); 

        //GET THE VALUE OF THE TOTAL NUMBER OF DATASETS INPUTS
        var GraphTotalDatasets = parseInt(document.forms.GraphData.TotalDatasets.value);

        //CREATE AN ARRAY USED TO GENERATE THE DIFFERENT COLOURS FOR THE GRAPH
        //THIS ARRAY HAS 15 COLOURS SO CAN HANDLE A MAX OF 15 DATASETS
        //COLOUR ORDER IS RED GREEN BLUE ORANGE PURPLE CYAN BLACK DARK GREEN DARK BLUE LIGHT BLUE YELLOW, DARK PURPLE DARK RED LIGHT GREY DARK GREY
        var GraphColourArray = ['#ff0000', '#00ff00', '#0000ff', '#ffd400', '#ff00ff', '#00ffff', '#000000', '#008620', '#001a9f', '#0096ff', '#dccf00', '#8d0088', '#890101', '#beb4b4', '#686868'];

        var GraphDatasetsArray = [];

        for (i=0; i < GraphTotalDatasets; i++)
        {
        var DataArray = document.forms.GraphData['GraphDatasetValues'+i].value.split(","); 
        GraphDatasetsArray[i] = 
                            {
                            label: document.forms.GraphData['GraphDatasetLabel'+i].value,
                            data: DataArray, 
                            fill: false, 
                            borderColor: GraphColourArray[i], 
                            backgroundColor: GraphColourArray[i],
                            pointBackgroundColor: '#ffffff', 
                            tension: 0,
                            }   
        }

        //SET THE GRAPH CONFIGURATION VALUES
        var LineChartConfig = {
                    type: 'line',
                data: {
                labels: GraphLabelArray,
                datasets: GraphDatasetsArray
                    }
            };


        var ctx = document.getElementById("ProjectActivityGraphCanvas").getContext("2d");
        window.myLine = new Chart(ctx, LineChartConfig);
        window.myLine.update();

        }
    }
    xmlhttp.open("GET", "ProjectManagement/HoursManagement_AJAX/Response_ProjectActivityGraph.asp?ProjectRef="+ProjectRef+"&StartDate="+StartDate+"&EndDate="+EndDate, true);
    xmlhttp.send();

}

Leave a comment