How to load data values from cookie into Chart.js

๐Ÿ‘:0

I tested your code on my browser and I found that you must pass a "String" to readCookie() function. Also, after returning value you should convert it to Array to use in the chart.js data. I did that with the help of JSON.parse. So here is the code that works for me:

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

document.cookie="dat=60, 80, 81, 56, 55, 40";
var dat = readCookie("dat");
var datArr = JSON.parse("[" + dat + "]");
console.log(datArr);
var chartData = {
    labels: ["January", "February", "March", "April", "May", "June"],
    datasets: [
        {
            fillColor: "#79D1CF",
            strokeColor: "#79D1CF",
            data: datArr//ref from cookie
        }
    ]
};

var ctx = document.getElementById("myChart1").getContext("2d");

const myLine = new Chart(ctx, {
    type: 'line',
    data: chartData,
    showTooltips: false,
    options: {
        scales: {
            y: {
                stacked: true
            }
        }
    }
});

// Uncaught TypeError: (new Chart(...)).Line is not a function
/*
var myLine = new Chart(ctx).Line(chartData, {
    showTooltips: false,
    onAnimationComplete: function () {

        var ctx = this.chart.ctx;
        ctx.font = this.scale.font;
        ctx.fillStyle = this.scale.textColor
        ctx.textAlign = "center";
        ctx.textBaseline = "bottom";

        this.datasets.forEach(function (dataset) {
            dataset.points.forEach(function (points) {
                ctx.fillText(points.value, points.x, points.y - 10);
            });
        })
    }
});
*/
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <canvas id="myChart1" height="300" width="500"></canvas>

    <script src="https://cdn.jsdelivr.net/npm/chart.js@3.6.0/dist/chart.min.js"></script>
    <script src="cod.js"></script>
</body>
</html>

I did not use your setting for chart because it gives me Uncaught TypeError: (new Chart(...)).Line is not a function error.

Leave a comment