Настройка Chart.js с помощью Ajax и переменных

Я не могу заставить свой Chart.js отображаться на моей веб-странице. Я использую два массива для данных/ярлыков и создаю график в функции onload js. Пробовал несколько различных методов из учебников и других постов в Stack.

HTML - это просто <canvas id="piee"></canvas>, и я принес chart.min.js в свой проект и загрузил скрипт как <script src="{% static "js/chart.min.js" %}"></script>

    window.onload = function () {
        console.log("Child: ", document.getElementById("piee"))
        var ctx = document.getElementById('piee').getContext('2d');

        var rep_name = $("#pie1").attr("data-rep-name")
        var ajax_url = $("#pie1").attr('data-ajax-url')
        var _data = []
        var _labels = []

        // Using the core $.ajax() method
        $.ajax({

            // The URL for the request
            url: ajax_url,

            // The data to send (will be converted to a query string)
            data: {
                name: rep_name
            },

            // Whether this is a POST or GET request
            type: "POST",

            // The type of data we expect back
            dataType: "json",

            headers: {'X-CSRFToken': csrftoken},

            context: this
        })
            // Code to run if the request succeeds (is done);
            // The response is passed to the function
            .done(function (json) {

                if (json.success == 'success') {

                    var newMale = json.malePerc
                    var newFemale = json.femalePerc
                    console.log(newMale, newFemale)
                    _labels.push("male", "female")
                    _data.push(parseFloat(newMale), parseFloat(newFemale))
                    var newUVB = json.uvbPerc
                    var newSize = json.specSize

                    console.log("data: " + _data)
                    var config = {
                        type: 'pie',
                        data: {
                            datasets: [{
                                data: _data,
                                backgroundColor: ['#ff0000', "#0000ff"],
                                label: "Temp"
                            }],
                            labels: _labels,
                        },
                        options: {
                            responsive: true
                        }
                    };

                    var myChart = new Chart(ctx, config)

                } else {
                    alert("Error: " + json.error);
                }
            })
    }
Вернуться на верх