Creating a line graph using chart.js and JSON dataset

I'm working on plotting a line graph using a JSON response from my MongoDB, but I keep encountering an error that indicates something might be wrong with my code structure.

Here's what I have attempted:

myurl = "/api/humidity"
$(function() {
    $.ajax({
        type: "GET",
        url: myurl,
        cache: false,
        dataType : "json",
        success: function (data1) {
            $.each(data1.when, function(position, when) {

                if (data1.when) {

                    chartData.labels.push(data1.when);
                } else {

                    chartData.labels.push('');
                }
                chartData.datasets[0].data.push(data.message);

            });
        }
    })
})


var chartData = {
    labels: [],
    datasets: [
        {
            label: "Humidity",
            fillColor: "rgba(220,220,220,0.2)",
            strokeColor: "rgba(220,220,220,1)",
            pointColor: "rgba(220,220,220,1)",
            pointStrokeColor: "#fff",
            pointHighlightFill: "#fff",
            pointHighlightStroke: "rgba(220,220,220,1)",
            data: []
        },

    ]
};


var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx).Line (chartData, {

});

I hope to optimize my code to iterate through all items in my database smoothly in the future.

This is how my JSON data is structured:

[{
    "_id": "585b544f5c86b6c8537c34d6",
    "topic": "Humidity",
    "message": 23,
    "when": "2016-12-22T04:19:27.000Z"
}, {
    "_id": "585b54505c86b6c8537c34d7",
    "topic": "Humidity",
    "message": 23,
    "when": "2016-12-22T04:19:28.000Z"
}, {
    "_id": "585b54515c86b6c8537c34d8",
    "topic": "Humidity",
    "message": 23,
    "when": "2016-12-22T04:19:29.000Z"
}, {
    "_id": "585b54525c86b6c8537c34d9",
    "topic": "Humidity",
    "message": 23,
    "when": "2016-12-22T04:19:30.000Z"
}, {
    "_id": "585b54535c86b6c8537c34da",
    "topic": "Humidity",
    "message": 23,
    "when": "2016-12-22T04:19:31.000Z"}]

Any assistance or suggestions would be greatly appreciated.

Answer №1

If you're looking to create a chart, consider using chart.js version 2.2

var data = [{
    "_id": "585b544f5c86b6c8537c34d6",
    "topic": "Humidity",
    "message": 23,
    "when": "2016-12-22T04:19:27.000Z"
}, {
    "_id": "585b54505c86b6c8537c34d7",
    "topic": "Humidity",
    "message": 23,
    "when": "2016-12-22T04:19:28.000Z"
}, {
    "_id": "585b54515c86b6c8537c34d8",
    "topic": "Humidity",
    "message": 23,
    "when": "2016-12-22T04:19:29.000Z"
}, {
    "_id": "585b54525c86b6c8537c34d9",
    "topic": "Humidity",
    "message": 23,
    "when": "2016-12-22T04:19:30.000Z"
}, {
    "_id": "585b54535c86b6c8537c34da",
    "topic": "Humidity",
    "message": 23,
    "when": "2016-12-22T04:19:31.000Z"
}]

var labelData = [];
var chartData = [];

for(var i =0; i < data.length; i++)
{
  labelData.push(data[i].when);
  chartData.push(data[i].message)
}

var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: labelData,
    datasets: [{
      label: 'Humidity',
      data: chartData,
      backgroundColor: "rgba(153,255,51,0.6)"
    }]
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.min.js"></script>
 <div>
    <canvas id="myChart"></canvas>
  </div>

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

Using the AngularJS filter within the controller to only display values that are not empty

I'm facing a challenge with filtering a JSON object array to only include objects where a specific field has a value. The field I need to filter by can have any type of value, so I can't use a specific match condition. My goal is to implement t ...

Is it possible to track keystrokes without the use of text input fields?

For various unimportant reasons, I need to use JavaScript to create links instead of using the anchor tag. I want the behavior to mimic the anchor tag, allowing users to open a link in a new tab when holding down the Ctrl key or in a new window when holdin ...

Bidirectional Communication between ExpressJS and Mongoose Models

Let's consider a scenario where we have a User model and a Book model in our express app, both referencing each other. How can mongoose middleware be utilized to ensure that both models stay synchronized when saving either one? It would be beneficial ...

Experiencing an unusual issue with grunt: The Gruntfile.js seems to be missing the 'flatten' method

Encountering an unusual error message while attempting to run grunt stated: TypeError: Object Gruntfile.js has no method 'flatten' Being a beginner with node.js, npm, and grunt, I believe my installation of node, npm, and grunt was done correctl ...

Can you explain the functions of this "malicious" JavaScript code?

I came across this piece of code on a website that labeled it as "malicious" javascript. Given my limited knowledge of javascript and the potential risks involved in trying out the code on my own site, I was hoping someone here might be able to shed some l ...

Serializing columns in SQL Server without using a key

In my database, there is a column labeled A which currently holds the value hello. I am looking to transfer this data into a new column called AJson and format it as ["hello"]. To accomplish this task, I need to use an SQL Server command. Alth ...

Dropped down list failing to display JSON data

I created a website where users can easily update their wifi passwords. The important information is stored in the file data/data.json, which includes details like room number, AP name, and password. [ {"Room": "room 1", "AP nam ...

Improving communication between Components in ReactJS

I am attempting to update the state from one component to another component. I wish for the state total on header.jsx to be updated when I click on the add to cart button on product.jsx Below is my code: index.jsx // Code for index.jsx goes here head ...

Step by step guide on adding content to a div by clicking a button, even after the page has already loaded

I have scoured the depths of the internet and forums but have yet to find a satisfactory solution to my problem. Hopefully, someone reading this can offer some help in resolving my issue. I manage a website that showcases concerts for various music groups. ...

Retrieve information from every nested array and present it in sequential order

I need to extract the index of each element in a nested array structure. For example, I have an array with 5 subarrays, each containing multiple elements. My goal is to retrieve the first element from each subarray, then the second element, and so on. Her ...

Using React to access a function from a different component in your application

I am working on implementing a topbar menu that requires access to a specific react component. The challenge I am facing is that within the topbar file, I do not directly render the components I need to interact with but still want to be able to call a fun ...

ran into the error that this state is not a function

Every time I run my code, I encounter the error message this.setState is not a function. Can anyone offer guidance on how to fix this issue? Thank you! spiele.listUsers(params, function(err, data) { if (err) console.log(err, err.stack); else con ...

Upload a JSON file to a server using a JavaScript app

I am in the process of creating a basic JavaScript application that allows users to annotate images stored on their machine and save these annotations as a JSON file. This application is lightweight and straightforward, not requiring an app server. Howeve ...

Using Mongoose's Find() method will retrieve the document that includes the specified value within an object

I am utilizing MongoDB and Express. Within my collection, I have all the countries which include states and cities. View a snapshot of part of the collection When using Find(), it returns all documents with all states and cities in the country instead of ...

Python JSON Data Pull Raises KeyError Exception

Struggling with my data extraction crawler, I find myself lost in categorizing the information I retrieve. The dict key I had hoped to use doesn't seem to fetch what I need. Specifically, I am trying to extract "member_id" and "vote_position." An exa ...

Finding the value of a JSON object when the key is constantly changing

Recently, I've been exploring information about various animals using the mediawiki API. Here is an example of a JSON query result for the animal "Camel": { "batchcomplete":"", "warnings":{}, "query":{ "pages":{ "6598":{ ...

Tips on extracting value from a pending promise in a mongoose model when using model.findOne()

I am facing an issue: I am unable to resolve a promise when needed. The queries are executed correctly with this code snippet. I am using NestJs for this project and need it to return a user object. Here is what I have tried so far: private async findUserB ...

How can I trigger an audio element to play using onKeyPress and onClick in ReactJS?

While attempting to construct the Drum Machine project for freeCodeCamp, I encountered a perplexing issue involving the audio element. Despite my code being error-free, the audio fails to play when I click on the div with the class "drum-pad." Even though ...

The process of embedding text into a Python script

When it comes to reading Python code from external files, there are various questions that arise: Python: How to import other Python files How to include external Python code to use in other files? The challenge lies in incorporating text snippets from ...

Unattended checkbox leads to AJAX feedback stalling with a spinning loading icon

Hello there! I have been working on a form that includes a checkbox, a textarea, and some input fields. I've managed to successfully submit all the form data to my localhost using POST to the database. However, I've encountered an issue when the ...