Development of a chart application involving frontend and backend components, utilizing chartjs for data visualization, mongodb for storage

As a beginner in generating charts using the ajax mechanism and chartjs, I've encountered an issue where the graphs are being plotted incorrectly. Any guidance on how to improve would be greatly appreciated. Thank you!

Here is my JavaScript code for plotting the chart:

      var ctx = document.getElementById('myChart').getContext('2d');
    
      $.ajax({
        url:"/dashboard",
        type:"POST",
        data: {},
        error: function() {
            alert("Error");
        },
        success: function(data, status, xhr) {
    
          debugger
          // declare all variables to draw chart
          var chartDim = {};      
          var chartDim = data.chartDim;
          var xLabels = data.labels;
    
          var vLabels = [];
          var vData = [];
    
          let newValues =[]
          // get from database to push to draw the chart
          for (const [key, values] of Object.entries(chartDim)) {
            vLabels.push(key);
            let newValues = values.map(myFunction);
            debugger;
            vData.push(newValues);
          } 
    
          debugger
          var myChart = new Chart(ctx, {
            data: {
            labels: xLabels,
            datasets: []
            },
            options: {
                responsive: false
            }
          });
          // draw to chart 
          debugger
          for (i= 0; i < vLabels.length; i++ ) {
            myChart.data.datasets.push({
            label: vLabels[i],
            type: "bar",
            borderColor: '#'+(0x1100000+Math.random()*0xffffff).toString(16).substr(1,6),
            backgroundColor: "rgba(249, 238, 236, 0.74)",
            data: vData[i],
            spanGaps: true
            });
            myChart.update();
          }
    
      }})

Answer №1

The reason for this issue is that when creating your chart, you are adding each data point as a separate dataset. To resolve this, all you need to do is utilize a single dataset and provide the data array to it in the following manner:

let myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: xLabels,
    datasets: [{
      borderColor: '#' + (0x1100000 + Math.random() * 0xffffff).toString(16).substr(1, 6),
      backgroundColor: "rgba(249, 238, 236, 0.74)",
      data: vData,
      spanGaps: true
    }]
  },
  options: {
    responsive: false
  }
});

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

Strategies for Mitigating Duplicate Requests in AngularJs with just one click

I am facing an issue with my AngularJS application where clicking on a link triggers the API call twice. I'm not sure why this happens and how to fix it. My service: SomethingService function getData() { return apiSettings.getApiInformation().t ...

Warnings about NgZone timeouts are displayed in Chrome DevTools even though the timeouts are actually executing outside of the

Is it common to receive a warning in Chrome DevTools like this? [Violation] 'setTimeout' handler took 103ms zone.js:1894 even when all timeouts are executed outside of ngzone? I personally follow this approach: this.zone.runOutsideAngular(() = ...

Obtaining JSON data in React Native without prior knowledge of the key

When I receive this type of data, the keys are common but the items vary. How can I extract and add this data to my list of categories? { "99": "Venues", "100": "Party Supplies", "101": "Enter ...

Utilizing jQuery ajax to dynamically update map markers on Google Maps at intervals

I am currently working on a project that involves updating a Google map with a marker at regular intervals. I have an Ajax request that retrieves a single latitude and longitude coordinate, but I'm struggling to display it on the map. One option coul ...

Potential causes for Chrome to send duplicate requests

In my nginx server logs, I have the following entries (IPs and paths altered for illustration purposes): 101.101.101.101 - - [15/Apr/2020:14:46:03 +0000] "GET /item/download-file/ready/5e971e290107e HTTP/2.0" 200 142940 "https://example.com/referer" "Mo ...

Dynamic content loading in Angular through HTML upon clicking

In the process of developing an Angular store, I aim to create anchor tags for each product so that clicking on a tag will display the selected product information in an HTML template below. Below is the current code snippet: (function() { var app = an ...

Issues have been reported with the functionality of the ng-click function in Angular JS

Having just started using AngularJs, I am facing an issue where the function is not being called when I click the button that I append. HTML </tbody> <tr> <td><input type="text" class="form-control" ng-model="contact.name ...

Spinning objects in three.js using tween.js to move around the global axis

Currently, I am working on tween-rotating a 3D cube. Thanks to this helpful post (How to rotate a object on axis world three.js?), I have successfully achieved rotation without any issues. Now, my goal is to transfer the rotation achieved through setFromRo ...

My Node.Js app refuses to run using my computer's IP address, yet works perfectly with localhost

My Node.js application is set up to listen on port 5050 of my machine: Visiting http://localhost:5050/myapp loads the app successfully. I am using the Express framework, so my listening framework looks like this: var server = app.listen(5050, '0.0.0 ...

Implementing conditional statements using jQuery for multiple selections

Having two unique IDs, I am planning to set a condition that corresponds with my query. $("#foo", "#bar").foo.bar({ baz: function() { if(selector == "#foo") { console.log("foo"); } else { console.log("bar"); } } }); ...

How can I achieve a similar functionality to array_unique() using jQuery?

When I select values from a dropdown, they are stored as an array like ["1","2","3"] Upon each change, the code below is executed to generate a new array based on the selected values: $('#event-courses-type').on('change', function(){ ...

Streaming data from a MongoDB database in a serverless Next.js application

Currently, I am referring to these resources in order to develop my Next-Mongo app without relying on a NodeJS server: https://www.mongodb.com/developer/how-to/nextjs-with-mongodb/ I have a question regarding data streaming. Is it possible to achieve rea ...

What is the best way to refresh my Material-UI checkboxes following updates to certain states in a React JS environment?

One of my latest projects involves an application that visualizes graphs, with all nodes originally colored blue. I included a component in the form of a checkbox that users can interact with to trigger a state change. This change dynamically alters the co ...

Please refresh the page after acknowledging the error

I am facing an issue with my PHP page that triggers a javascript alert upon encountering an error. if (strpos($this->color,':') !== false) { echo '<script type="text/javascript">alert("Please use the RBG format of 255:2 ...

What is the best way to process an API call entirely on the server without revealing it to the client?

Seeking guidance on a technical issue I've encountered. On my website, x.com, a form submission triggers an API call to y.com, yielding a JS hash in return. The problem arises when Adblocker Plus intercepts the content from y.com, causing it to be bl ...

Deploying an AngularJS 1.x application bundled with Webpack to Tomcat server

I've scoured the depths of Google and combed through the official documentation for Webpack, but I’ve yet to stumble upon a tutorial, guide, or plugin that addresses this particular issue. Does anyone have any experience with this problem, or should ...

The display of options in React Bootstrap typeahead is not functioning properly

When I try to implement React Bootstrap Typeahead, the options do not appear in the Typeahead component upon page load. Here is a snippet of my code: const React = require('react'); ... (code continues) The options are generated as follows: [ ...

The date-fns parse function will retrieve the value from the previous day

When attempting to parse a date using the date-fns library, I am encountering an issue where the resulting date is one day prior. How can this be resolved in order to obtain the correct result? start = '2021-08-16' const parseStart = parse(start, ...

Demonstrate how to pass a newline character from Ruby on Rails to JavaScript

I am working with a .js.erb file that is activated by a JavaScript function. Within this js.erb file, I have the following snippet of code: event = <%=raw @event.to_json %> $('#preview-event-body').html(event.body); The value of event.bo ...

Include onload to element without running it in Puppeteer

I am currently developing a web scraping tool using Puppeteer. Once the webpage is fully loaded, I need to update the HTML code and include an onload event for certain elements. The issue is that in Puppeteer, the onload event is actually triggered automa ...