Make time as label for Chart.js


This is my first time working with Chart.js in order to make a chart for my data. I am looking to make a chart from some specific data from my database which I have exported in an array during the processing in php. However I feel kinda lost. So to be more specific:

I have an array that looks like this:

Array ( [0] => 2021-07-02 [1] => 2021-07-20 [2] => 
06:47 [3] => 23:47 [4] => 
09:47 [5] => 21:47 [6] => 
18:27 [7] => 21:47 [8] => 
03:47 [9] => 06:50 [10] => 
00:48 [11] => 21:48 [12] =>
171.2786 [13] => 170.9501 [14] => 170.2825 [15] => 173.1435 [16] => 171.4377 )

The first two elements are some datetimes and the following are time intervals selected by the user in order to calculate an average of the values between the inputs (an entry in the table looks like this):

+-------------+--------------------+------+-------+
| ID          | datetime           | Type | Value | 
+-------------+--------------------+------+-------+
| 202106250446| 2021-06-25 04:46:00| 0    | 194   | 
+-------------+--------------------+------+-------+

I want to make a chart that takes as label the time slots (like 1 label should look like 06:47-23:47) and and which has as its value the first number element (for this example 171.2786)

I parse this array from php with json (jvs is the name of the array)

<script type="text/javascript">
    var obj = <?php echo json_encode($jvs); ?>;
</script>

and opened a app.js file but I struggle understanding how to concatenate and write the labels and data (since it’s my first time doing this)

$(document).ready(function(){
    $.ajax({
      url: "http://localhost/chartjs/average.php",
      method: "GET",
      success: function(jvs) {
        console.log(jvs);
        var interval = [];
        var average = [];
  
        { here is the part of code that cannot figure it out}
  
        var chartdata = {
          labels: interval,
          datasets : [
            {
              label: 'Interval chosen',
              backgroundColor: 'rgba(200, 200, 200, 0.75)',
              borderColor: 'rgba(200, 200, 200, 0.75)',
              hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
              hoverBorderColor: 'rgba(200, 200, 200, 1)',
              data: average
            }
          ]
        };

Thank you and please forgive me if I’m making rookie mistake, I’m still learning 😀

Source: JavaSript – Stack Overflow

November 8, 2021
Category : News
Tags: chart.js | charts | graphics | javascript

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.