Chart.js Setup Using Ajax & Variables

I cannot get my Chart.js to show up on my webpage. I am utilizing two arrays for data/labels and am creating the chart in an onload js function. Tried several different methods from tutorials and other Stack posts.

HTML is just <canvas id="piee"></canvas> and I brought chart.min.js into my project and load the script as <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);
                }
            })
    }
Back to Top