ChartJS creates individual charts for each JSON object, rather than generating them only upon hovering

I am completely new to using ChartJS and JavaScript, as I attempt to create some charts for my django application. I'm facing an issue while trying to generate multiple charts from distinct JSON objects within the same line. Currently, the same chart is being generated, which switches to the second view upon hovering. What I desire is one chart reflecting the first view or initial JSON object, and another chart displaying the second view/second JSON object. Take a look at my code snippet along with some sample data below:

data = [{'title': 'team', 'labels': ['Team score'], 'default': [50.0], 'title': 'single': 'labels': ['Single score'], 'default': [37.5]}]

JS:
var defaultData = [];
var labels = [];


function loadDashboard() {
    $.ajax({
        method: "GET",
        url: endpoint,
        success: function(data) {
            for (var key in data) {
                if (data.hasOwnProperty(key)) {
                    var objName = Object.keys(data)[0];
                    var val = data[key];
                    labels = val.labels;
                    defaultData = val.default;
                    updateChart(label=labels, data=defaultData, elementId=objName)
                }
            }
        },
        error: function(error_data) {
            console.log("error");
            console.log(error_data)
        }
    });
}

function updateChart(label, data, elementId) {
    var tableName = document.getElementById(elementId).getContext('2d');
    var elementId = new Chart(tableName, {
        type: 'bar',
        data: {
            labels: label,
            datasets: [{
                label: 'NPS Score',
                data: data,
                backgroundColor: [
                    'rgba(255, 99, 132, 0.2)',
                    'rgba(54, 162, 235, 0.2)',
                    'rgba(255, 206, 86, 0.2)',
                    'rgba(75, 192, 192, 0.2)',
                    'rgba(153, 102, 255, 0.2)',
                    'rgba(255, 159, 64, 0.2)'
                ],
                borderColor: [
                    'rgba(255,99,132,1)',
                    'rgba(54, 162, 235, 1)',
                    'rgba(255, 206, 86, 1)',
                    'rgba(75, 192, 192, 1)',
                    'rgba(153, 102, 255, 1)',
                    'rgba(255, 159, 64, 1)'
                ],
                borderWidth: 1
            }]
        },
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero:true
                    }
                }]
            }
        }
    });
}

$(document).ready(function() {
    loadDashboard()
});

HTML

 <div class="row">
     <div class="col-sm-6" id="teamScore" url-endpoint="{% url 'nps-dashboard-data' %}">
         <canvas id="teamScoreChart" width="400" height="400"></canvas>
     </div>
     <div class="col-sm-6" id="singleScore">
         <canvas id="singeScoreChart" width="400" height="400"></canvas>
     </div>
     <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
     <script src="{% static 'js/dashboard.js' %}"></script>
 </div>

Answer №1

After some investigation, I managed to solve the issue. For those who are curious about the solution:

const defaultDataValues = [];
const labelsList = [];


function initializeDashboard() {
    $.ajax({
        method: "GET",
        url: endpoint,
        success: function (receivedData) {
            for (let key in receivedData) {
                if (data.hasOwnProperty(key)) {
                    console.log(receivedData[key])
                    let value = receivedData[key];
                    let objectName = value['title']
                    labelsList = value.labels;
                    defaultDataValues = value.default;
                    updateVisualization(labelsList, defaultDataValues, objectName)
                }
            }
        },
        error: function (errorResponse) {
            console.log("An error occurred");
            console.log(errorResponse)
        }
    });
}


function updateVisualization(labelsArray, dataValues, elementId) {
    let visualizationElement = document.getElementById(elementID).getContext('2d');
    let updatedChart = new Chart(visualizationElement, {
        type: 'bar',
        data: {
            labels: labelsArray,
            datasets: [{
                label: 'Scores',
                data: dataValues,
                backgroundColor: [
                    'rgba(255, 99, 132, 0.2)',
                    'rgba(54, 162, 235, 0.2)',
                    'rgba(255, 206, 86, 0.2)',
                    'rgba(75, 192, 192, 0.2)',
                    'rgba(153, 102, 255, 0.2)',
                    'rgba(255, 159, 64, 0.2)'
                ],
                borderColor: [
                    'rgba(255,99,132,1)',
                    'rgba(54, 162, 235, 1)',
                    'rgba(255, 206, 86, 1)',
                    'rgba(75, 192, 192, 1)',
                    'rgba(153, 102, 255, 1)',
                    'rgba(255, 159, 64, 1)'
                ],
                borderWidth: 1
            }]
        },
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero:true
                    }
                }]
            }
        }
    });
}


$(document).ready(function() {
    initializeDashboard()
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am unable to apply CSS to style my <div> element

I've run into a snag with my coding project, specifically when attempting to style my div. Here is the code I have so far: All CSS rules are applying correctly except for the .chat rule. Can someone help me figure out what I'm doing wrong? var ...

Steps to create a hover effect similar to that of a website (increasing grid size on hover)

Looking to create a hover effect for my boxes similar to the one on this website: I've examined the code of the website above and searched extensively for a similar feature without any luck. Could anyone offer assistance with this, please? ...

Vuetify - Issue "An extra loader may be required to manage the output of these loaders."

I am currently utilizing Materio Template Vuetify along with Babel. To begin, I serve the template by using yarn serve. Upon completion of the packaging process, I encountered several errors prompting me to include an additional loader. Here is the conte ...

Creating various visualizations using React

I am new to React, Highcharts, and UI development in general. My goal is to render multiple charts from an array of data. However, I'm currently facing an issue where only the last chart - based on the last data in the array - is displayed on the page ...

Updating dropdown selection with JavaScript

I have a dropdown select menu with two options. I am using JavaScript to retrieve the selected value from the drop-down menu and display it in a text area. Here is my code: $(document).ready(function () { $('#pdSev').change(function () { ...

Update the innerHTML content dynamically every 5 seconds with Vue.js

I'm working on a new website and I'd like to spice things up by changing the header text with a random word every 5 seconds. Here's the starting point: const header = document.querySelector('.header') const needs = ['jacket& ...

Obtaining an element within an object using a jQuery selector

I'm currently attempting to utilize a jQuery selector on data received from an ajax call. Below is the code snippet I am working with - $.ajax({ url: 'moo.html', success: function ( code ) { var divs = $(code).filter(functi ...

I'm having trouble getting the drag event to work for Three.js trackball controls within a UIkit

The issue at hand involves a fullscreen Three.js canvas that is functioning perfectly, but there are limitations when displaying a preview in a UIkit modal – zooming works, but panning does not. JS: Renderer and Controls renderer = new THREE.WebGLRende ...

Whenever my NodeJs encounters an unhandledPromise, it throws an error

https://i.sstatic.net/w6sa9.png exports.createNewTour = async (request, response) => { try { const newlyCreatedTour = await Tour.create(request.body); res.status(201).json({ statusCode: "success", details: { tours ...

Rebind my ASP.Net script using JavaScript after a postback

Upon reviewing this article, I have come to understand that when using updatepanel for postback, the javascript bindings are lost. The issue I am facing is that my javascript code resides in a file called jscolor.js. The connection between my asp page and ...

Initiating a quick route refresh - Redirecting the traffic

Is it possible to change the URL address while processing a request in Express? I am looking for a simple redirect implementation that allows me to modify the current URL and restart the route matching process. Here's an example of what I'd like ...

Capture data from ajax effectively by extracting and executing manipulations seamlessly

I have a project where I need to retrieve images from a database using Ajax and display them using a carousel plugin. This is the process: An image URL is saved to the database by an admin The frontend script makes an Ajax call to a PHP file and retrieve ...

The property of Three.js Quaternion is immutable and cannot be reassigned

I'm attempting to develop a class (using three.js) that utilizes an array containing vector names to compare with an array containing a set of 3D vectors in order to generate a mesh of a flat face. However, I am encountering an error. Uncaught TypeEr ...

Updating Vue.js Component Data

I have set up a basic Example Component which is bound to a Vue Instance as shown below: <template> <div class="container-fluid"> <div class="row"> <div class="col-md-8 col-md-offset-2"> < ...

Guide on how to implement AJAX functionality for the shopping cart items and total amount

I am currently working on updating the cart items and total on my website using ajax whenever a user clicks on "add to cart". I have implemented the following code in the function.php file of my WordPress site: add_filter('wp_nav_menu_items',&ap ...

How can I determine in JQUERY when all ajax requests on a page have finished processing?

Is there a way in JQUERY to determine when all ajax calls on a page have finished? I need to run a specific method once all the ajax calls are done. ...

having difficulty sorting items by tag groups in mongodb using $and and $in operators

I'm currently trying to execute this find() function: Item.find({'tags.id': { $and: [ { $in: [ '530f728706fa296e0a00000a', '5351d9df3412a38110000013' ] }, { $in: [ ...

React JS component experiencing issues with Material UI modal functionality

Attempting to reproduce the material ui modal example has proven to be a challenge for me. Initially, I encountered an error stating "Cannot read property 'setState' of undefined" which I managed to resolve. However, even after resolving this iss ...

Issues with texturing in ThreeJS

I am currently working on a project in threejs that involves loading a .stl file. However, I have run into an issue where the loaded object automatically changes color from its original one. I would like to keep the original color of the object. What steps ...

Angular - the utilization of expressions in view templates

Exploring Angular for the first time and attempting to create a Single Page Application (SPA). I have included the route module, which seems to be functioning properly. However, the templates are not interpreting Angular expressions as expected - for examp ...