Chartjs-Javascript / JSON error: TypeError: myObj is undefined

0👍

You only set your myObj variable when this.readyState == 4 && this.status == 200:

if (this.readyState == 4 && this.status == 200) {
    var myObj = JSON.parse(this.responseText);
}

However, the rest of the xmlhttp.onreadystatechange function will still run for other readyState values and in those cases myObj will be undefined.

Therefore, the whole function body should be within the if condition:

xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myObj = JSON.parse(this.responseText);

        var ctx = document.getElementById("overviewChart");

        var data = {
            labels: [myObj[0][0], myObj[0][1], myObj[0][2], myObj[0][3], myObj[0][4]],
            datasets: [
                {
                    backgroundColor: "rgba(255, 120, 42, 0.7)",
                    hoverBackgroundColor: "rgba(255, 120, 42, 1)",
                    borderColor: "rgba(255, 120, 42, 0.9)",
                    borderWidth: 3,
                    label : "Offen",
                    data: [myObj[1][0], myObj[1][1], myObj[1][2], myObj[1][3], myObj[1][4]]
                },
                {
                    backgroundColor: "rgba(50, 255, 50, 0.7)",
                    hoverBackgroundColor: "rgba(50, 255, 50, 1)",
                    borderColor: "rgba(50, 255, 50, 0.9)",
                    borderWidth: 3,
                    label: "Bestätigt",
                    data: [myObj[2][0], myObj[2][1], myObj[2][2], myObj[2][3], myObj[2][4]]
                },
                {
                    backgroundColor: "rgba(255, 30, 30, 0.8)",
                    hoverBackgroundColor: "rgba(255, 30, 30, 1)",
                    borderColor: "rgba(255, 30, 30, 0.9)",
                    borderWidth: 3,
                    label : "Storniert",
                    data: [myObj[3][0], myObj[3][1], myObj[3][2], myObj[3][3], myObj[3][4]]
                }
            ]
        }
    }
};

Leave a comment