Unable to transfer information to chart.js graph

I've been struggling to pass my data to the graph, but it just won't cooperate. Interestingly, if I manually input numbers like

data: [1,2,3]

then it works perfectly fine. In my code, you'll notice that I've console.logged both data.weight and data.goal, and they show up in the console as expected.

Take a look at the code snippet below:

var endpoint = '/api/data';
    var defaultDataW = [];
    var defaultDataG = [];
   
    $.ajax({
        method: 'GET',
        url: endpoint,
        success: function(data){
            console.log(data.weight);
            console.log(data.goal);
            defaultDataW = data.weight;
            defaultDataG = data.goal;
            var graph = document.getElementById("weight-graph");

            Chart.defaults.global.defaultFontFamily = "Lato";
            Chart.defaults.global.defaultFontSize = 18;

            var dataFirst = {
                label: "Your Weight (Kg)",
                data: defaultDataW,
                lineTension: 0,
                fill: false,
                borderColor: 'red'
            };

            var dataSecond = {
                label: "Your Goal (Kg)",
                data: defaultDataG,
                lineTension: 0,
                fill: false,
                borderColor: 'blue'
            };

            var DateData = {
                labels: [],
                datasets: [dataFirst, dataSecond]
            };

            var chartOptions = {
                legend: {
                    display: true,
                    position: 'top',
                    labels: {
                        boxWidth: 80,
                        fontColor: 'black'
                    }
                }
            };

            var lineChart = new Chart(graph, {
                type: 'line',
                data: DateData,
                options: chartOptions
            });
        },
        error: function(error_data){
            console.log("Error");
            console.log(error_data);
        }
    })

Answer №1

While you are on the right track, there is a key issue with how you are handling the data type...

Here's what you are doing correctly:

var defaultDataW = [];

This ensures that your data is stored as an ARRAY.

However, in your ajax request, you are assigning a single value to the variable:

defaultDataW = data.weight;

Based on your comments, it seems that 'data.weight' is actually an INTEGER.

When you try to use this integer as data in a Chart like this:

data: defaultDataW,

It won't work properly (which is not surprising).

Chart.js requires at least an ARRAY to function correctly - https://www.chartjs.org/docs/master/general/data-structures/

So, how can you resolve this issue?

The solution is quite straightforward...

In your ajax call, instead of replacing the array with an integer, add the integer to the existing array:

defaultDataW.push(data.weight);

If you anticipate adding more code later or organizing your project differently, consider learning how to clear the array before performing a push operation. Although it may not be necessary in your current setup, I'll explain it here for reference and future scenarios.

Prior to pushing values into the array (especially within loops), you may need to empty the array:

defaultDataW.length = 0;

This action will reset the array, allowing you to accurately populate it with new data. If you skip clearing the array and proceed with pushing values, the old data will remain along with the new data (this might be advantageous in certain situations, but not in this specific case).

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

Open the provided URL in the web browser

Is it possible to open the URL in the web browser? $(document).ready(function(){ $(document).on('click','#see',function(){ var ID = $("#rowid").val(); $.ajax({ type:'GET', url:&ap ...

Utilizing the power of jQuery within three.js

Thank you once again for your previous assistance, but I find myself in need of your expertise once more. I have successfully added markers to my map as desired. However, these markers now require functionality to be clickable. Specifically, when clicked, ...

Trouble with Javascript when loading Ajax page

We have created a form building module similar to Google Forms using PHP. Everything is functioning properly when adding and creating the form. For editing, we have implemented a modal popup loading content through Ajax. MAIN.PHP $('a[data-toggle=m ...

Issue encountered when compiling a node.js file on Windows 10, resulting in error code 800A03EA

Recently I downloaded and installed Node.js for Windows 10 (x64), accepting all the default settings. C:\WINDOWS\system32>node -v v12.13.0 C:\WINDOWS\system32>npm -v 6.12.0 Next, I decided to test it out by running their "hello ...

Understanding the structure of JSON files without prior knowledge

Without any prior knowledge of the contents, I am seeking to understand the structure of a JSON object. For example, I could receive: [{"x":0,"y":0.4991088274400681,"z":7.489443555361306}, {"x":0,"y":0.7991088274400681,"z":7.489343555361306},{"x":0,"y":0. ...

Dealing with null values in nested arrays in Vue

Coming from a background in Ruby code, I have a question for you. I recently received this API response: [{:id=>"61b79d02a0f6af001374744e", :name=>"Waffle Crewneck", :code=>"FW22KS000", :result=>{"status ...

Conceal the results of echoing json_encode

One dilemma I encountered was passing an array from PHP to JavaScript using json_encode and ajax. The only method that seemed available was to use echo json_encode($var) This approach printed out the contents of $var on the page due to the echo statement ...

What is the best way to retrieve a parameter in jQuery ajax?

Seeking assistance with retrieving the parameter sent via ajax... url: test.htm?a=1&b=2&c=3 I am trying to access the value of b. ...

differences between object access and array access in JavaScript

I have been accumulating a series of data that increases gradually in size. Now, I am faced with the task of finding a specific row within this data using its unique Id. In my quest to optimize this search process, I have considered two potential options. ...

function called with an undefined response from ajax request in React

Hello, why am I getting the response "callback is not defined"? Component 1: console.log(getUserGps()); Component 2: import $ from 'jquery' export const getUserGps = () => { $.ajax({ url: "https://geolocation-db.com/jsonp", ...

Issues encountered with Three.js MeshBasicMaterial functionality

I am currently working on generating a texture using Three.js. The texture_f1 source I am using is a .png file, which allows the background to show through. The issue arises when attempting to set the background color using color: 0xffffff in conjunction ...

Invoke a method within an *ngIf statement in Angular 5

Suppose I have the following code snippet: <div *ngIf="item">lorem ipsum</div> Is there a way to trigger a function if the *ngIf condition is true? Perhaps something like this... <div *ngIf="(item) : callFunction() ? ...">lorem ipsum& ...

Is the RouterModule exclusively necessary for route declarations?

The Angular Material Documentation center's component-category-list imports the RouterModule, yet it does not define any routes or reexport the RouterModule. Is there a necessity for importing the RouterModule in this scenario? ...

Shopping cart feature in PHP - Ajax response only functioning once

I'm in the process of developing a shopping cart. I start by adding products to the cart, then use Ajax to dynamically update the quantity when it changes. Everything works smoothly after the first change, but subsequent quantity updates do not refres ...

Tips for converting a URL to the correct route in emberjs when the location type is set to history

After creating a basic Ember.js application and setting the router location type to 'history', I encountered an issue with the generated URLs. Instead of the expected URL format like http://localhost/#/post/1, the Ember.js application was changi ...

"Converting an object to a JSON string using URLSearchParams: A step-by

I am currently working on a piece of code that retrieves all the input types from a form const form = document.querySelector('form'); const data = new URLSearchParams(new FormData(form).entries()); My main concern is how to convert the above ...

Using ng-style to apply a background image with a dynamic id

Hey there, I'm facing an issue here. The link provided below seems to not be working properly. Even though the id is set correctly within the scope, it seems like there might be a parsing error occurring. Any thoughts on what might be causing this pro ...

Determine the number of items (within an array) that were created within the past few days, weeks, and months leading up to the 'current time'

Having an array filled with objects containing timestamps: Here is a glimpse of the data: const dataList = [ { _id: "602102db3acc4515d4b2f687", createdDt: "2021-02-08T09:22:35.000Z", }, { _id: "6021024da706a260d89 ...

Navigating through JavaScript links in Selenium (Scrapy) and returning to the initial page: A step-by-step guide

Having some difficulties with pages that have javascript links embedded in them. This issue arises when the page contains a list of cities with javascript in their links. Each link needs to be navigated individually, scraping information and then returning ...

Ensure one div scrolls independently while the other remains fixed using Bootstrap

I am currently in the process of constructing a web page with Bootstrap 4. The layout consists of two columns, each contained within individual divs. My requirement is for the content on the right side to be scrollable while the content on the left remains ...