Skip to content
Advertisement

Are you required to make an http request when trying to use Chart.js?

I followed a tutorial video that showed how to set up Chart.js with Django, using Jquery and API function calls to a page on my site. However, I don’t need to make these function calls to get the data, as the data are associated with my objects themselves. When I get rid of the http function call and just write the code instead, my graphs don’t show up. Is the http format required? A working version I have is:

            <script> 
            var endpoint = ''/api/chart/data/'';

            fetch(endpoint, {
                method: "GET",
            }).then(response => response.json())
            .then(
                data => {
                console.log('Success:', data);
                graph_data = {...}
                var ctx{{ forloop.counter }} = document.getElementById("myChart{{ forloop.counter }}");

                var myChart =  new Chart(ctx{{ forloop.counter }}, graph_data); 
                })
                .catch((error) => {
                    console.log("Error:")
                    console.log(error);
                });

                        
        </script>
        <div style="width: 60%; float:left;">
            <canvas id= "myChart{{ forloop.counter }}" style = "padding-bottom: 9px;"></canvas>
        </div>

Could this instead just be:

                console.log('Success:', data);
                graph_data = {...}
                var ctx{{ forloop.counter }} = document.getElementById("myChart{{ forloop.counter }}");

                var myChart =  new Chart(ctx{{ forloop.counter }}, graph_data);
    <div style="width: 60%; float:left;">
        <canvas id= "myChart{{ forloop.counter }}" style = "padding-bottom: 9px;"></canvas>
    </div> 

The error I am getting is

Chart.min.js:14 Uncaught TypeError: Cannot read property 'length' of null
    at Object.acquireContext (Chart.min.js:14)
    at new t.Controller (Chart.min.js:11)
    at new t (Chart.min.js:12)
    at (index):616

Advertisement

Answer

The HTTP call is not part of anything related to Chart.js.

The reason why it’s not working is you’re calling “getElementById” before the DOM element you’re looking for has been loaded.

The reason why it works when you are using the fetch call is that while you are making the HTTP request, you are giving the DOM time to load your canvas.

It’s usually best to wait for your whole DOM to load before running any javascript.

Solution

Move the script tag to the bottom of the page OR Add “defer” to your script tag which will tell the browser to start running the javascript after the DOMContent has been parsed.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement