Receive Real-Time Notifications -> Update Title Using an Array Retrieved from a JSON File

I've been working on updating a live chart every 5 seconds with new data from the database. While I could easily update the information, I encountered a problem when trying to set a path within the chart options for tooltips callbacks afterTitle. Specifically, I need to access an array inside this callback function and pass data from the JSON response into it.

To achieve this, I already have a function that updates the data and labels successfully. Now, within this function, I need to create a path to afterTitle so that I can include the fifth array containing the required data. Despite being able to update the data and labels in the function, I'm facing challenges in incorporating another array without causing the chart to blink with each update.

Below is the example code snippet where I tried to incorporate the necessary changes:

$.getJSON('loadchart.php', function(response) {
          myLineChart.data.datasets[0].data = response[0];
          myLineChart.data.datasets[1].data = response[1];
          myLineChart.data.datasets[2].data = response[2];
          myLineChart.data.datasets[3].data = response[3];
          myLineChart.data.labels = response[4];

          //The response array that I need is response[5];
          //myLineChart.options.tooltips.callbacks[1] = return response[tooltipItem[0]['index']]; 
          myLineChart.update();
        });

Here's an overview of my Chart structure including the defined path:

 <script>

    function loadData() {
      $.getJSON('loadchart.php', function(response) {
        myLineChart.data.datasets[0].data = response[0];
        myLineChart.data.datasets[1].data = response[1];
        myLineChart.data.datasets[2].data = response[2];
        myLineChart.data.datasets[3].data = response[3];
        myLineChart.data.labels = response[4];

        myLineChart.update();
      });
    }

    loadData();
    setInterval(loadData, 5000);

    var lbl = [];
    var ctx1 = document.getElementById('mychart1').getContext('2d');

    var myLineChart = new Chart(ctx1, {
        type: 'line', 
        data: {
          labels: lbl,
          datasets: [
            {
              label: "Current 1",
              data: [],
              borderWidht: 6,
              borderColor: 'red',
              backgroundColor: 'transparent'
            },
            {
              label: "Current 2",
              data: [],
              borderWidht: 6,
              borderColor: 'blue',
              backgroundColor: 'transparent'
            },
            {
              label: "Current 3",
              data: [],
              borderWidht: 6,
              borderColor: 'green',
              backgroundColor: 'transparent'
            },
            {
              label: "Total Current",
              data: [],
              borderWidht: 6,
              borderColor: 'black',
              backgroundColor: 'transparent'
            },
          ]            
        },
        options: {
          animation:{
            update: 0
          },
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: true
              }
            }],
            xAxes: [{
              gridLines: {
                display: false
              }
            }]
          },

          title: {
            display: true,
            fontSize: 20,
            text: "Current Graph"
          },

          labels: {
            fontStyle: "bold",
          },

          layout: {
            padding: {
              left: 0,
              right: 0,
              top: 0,
              bottom: 0
            }
          },
          tooltips: {
            enabled: true,
            mode: 'single',
            responsive: true,
            backgroundColor: 'black',
            titleFontFamily: "'Arial'",
            titleFontSize: 14,
            titleFontStyle: 'bold',
            titleAlign: 'center',
            titleSpacing: 4,
            titleMarginBottom: 10,
            bodyFontFamily: "'Mukta'",
            bodyFontSize: 14,
            borderWidth: 2,
            borderColor: 'grey',
            callbacks:{
              title: function(tooltipItem, data) {
                  return data.labels[tooltipItem[0].index];
              },
              afterTitle: function(tooltipItem, data) {
                var tempo = [];
                return tempo[tooltipItem[0]['index']];
              },
              label: function(tooltipItem, data) {
                    var label = data.datasets[tooltipItem.datasetIndex].label || '';                  
                    if (label) {
                        label += ': ';
                    }
                    label += (tooltipItem.yLabel)+"A";                  
                    return label;
              }
            }
          },
          aspectRatio: 1,
          maintainAspectRatio: false
        }
    });
</script>

The specific part requiring modification is shown here:

afterTitle: function(tooltipItem, data) {
                var tempo = [];
                return tempo[tooltipItem[0]['index']]; 

Answer №1

If you want to display a clock, you can adjust the settings to show it for 5000 seconds and then update your chart. It is recommended to incorporate AJAX functionality to make it work asynchronously.

            <!DOCTYPE html>
            <html>
            <head>
            <script>
            function startTime() {
              var today = new Date();
              var h = today.getHours();
              var m = today.getMinutes();
              var s = today.getSeconds();
              m = checkTime(m);
              s = checkTime(s);
              document.getElementById('txt').innerHTML =
              h + ":" + m + ":" + s;
              var t = setTimeout(startTime, 500);  //<----  !!!
            }
            function checkTime(i) {
              if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
              return i;
            }
            </script>
            </head>

            <body onload="startTime()">

            <div id="txt"></div>

            </body>
            </html>

Answer №2

After mentioning the afterTitle function, the task is to create an array and pass it from the JSON to an array inside the callback. The issue arises when creating an array named tempo and incorrectly handling it as an object by calling tempo[tooltipItem[0]['index']];. The correct approach should be to push the object tooltipItem[0]['index'] into the tempo array.

To rectify this issue, please replace the afterTitle function with the following code:

afterTitle: function(tooltipItem, data) {
            var tempo = [];
            return tempo.push(tooltipItem[0]['index']); 

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

Unable to locate property 'location' due to being undefined

When trying to use the react-router-dom 4.0.0 library, an error was encountered: Uncaught TypeError: Cannot read property 'location' of undefined The issue seems to be with browserHistory. Previously, I had been using react-router 2.x.x witho ...

Angular not displaying retrieved data

Having an issue with fetching data from an API using Angular. Although the console log confirms that the data is successfully fetched, it doesn't display on the page. Any assistance would be greatly appreciated. Take a look at my code: app.component. ...

Adjust size of element in relation to Background Cover using jQuery

Can you help me solve a challenge I'm facing? I have a website with a fullsize background image, and I need to attach a div to a specific position on the image while ensuring that it scales in the same way as the background image with the "background ...

configure dynamic content within the slider element

Currently, I am experimenting with two jQuery plugins (awkward/Coda Slider 3) to implement a sliding effect for DIV content. Everything seems to be working smoothly until I attempt to set dynamic content (using JavaScript) after creating the plugin object. ...

Prevent MUI Autocomplete from closing when the option menu is opened with blur

Seeking assistance with modifying an autocomplete menu to include a dropdown for each item. Issue arises after trying to open the additional menu as it triggers an immediate closure of the autocomplete. For reference, attached is an image showcasing the i ...

Navigating through duplicate keys in node/jade

I have a collection of mongoose model objects retrieved from a mongo database (using Model.find()): [ {_id: '...', type: 'colour', value: 'red'}, {_id: '...', type: 'colour', value: 'blue&apos ...

developing authentication codes using javascript

Currently, I am working on developing a sign-up system that allows users to easily generate a random string with the click of a button. The generated string can then be shared with non-users who wish to sign up. The new user will need to enter their chose ...

Check if all items in the array exist in Mongodb, then update them; if not, insert

In my database, I have a collection of tags and I want to perform the following actions when a user enters an array of tags: If a tag in the array already exists, update its count If a tag in the array does not exist, insert it with a count of 0 Current ...

Show a modal component from another component in Angular 2

As a newcomer to Angular, I'm working on a modal component that changes from hiding to showing when a button with (click) is clicked. The goal is to integrate this modal into my main component, allowing me to display the modal on top of the main conte ...

What is the smallest server.js file needed to run a react/redux application?

I have successfully configured my project using webpack and babel for ES6 transpilation with the specified presets: { "presets": ["react", "es2015", "stage-1"] } My webpack production configuration is structured as follows: var path = require('pa ...

JavaScript table search feature for novices - finding results

I am relatively new to this, but I am working on improving the workflow within my company. I found some code at this link in order to create an internal site for searching current part numbers. However, my employees are looking for parts based on descripti ...

How to easily transfer a JSON file to a server using Vue and Node.js

As a newcomer to the world of Node.js and Vue development, my goal is to establish a seamless process for users to create and upload a JSON file to the server when they save data in a form. This process should occur effortlessly in the background, allowing ...

Error: The property 'setCrossOrigin' is not defined and cannot be read

When I try to run both .obj and .mtl files together, I encounter an error, whereas running just the .obj loader works fine. The specific error message that appears is: MTLLoader error Below is the code snippet I am using to load the .obj and .mtl files: ...

JavaScript: Filtering list by elements that contain a certain value

I have the following collection of objects: [ { employeeId:1 employeeName:"ABC" }, { employeeId:2 employeeName:"ABD" }, { employeeId:3 employeeName:"FEW" }, { employeeId:4 employeeName:"JKABL" },] I am looki ...

Fetch a single random profile image from a Facebook user's list of friends using Javascript

I'm currently facing an issue with displaying a random profile picture of the user's friends on Facebook. I attempted to troubleshoot it myself but ended up crashing the login button and now it's not functioning properly. Can someone please ...

Content formatted with a gap

I wish to include a gap between each sample usage with markdown. For instance: .kick Sarah, .kick John, .kick Mary .setDescription(`**Usage :** \`${settings.prefix}${command.help.name} ${command.help.usage}\`\n**Example :** \`${setting ...

I am looking to generate a PostgreSQL view that can extract the contents of a JSON column

This query creates a view in PostgreSQL that displays data from JSON columns (labtestgroup and price). CREATE OR REPLACE VIEW public.orders_with_prices AS SELECT o.id, replace(''::text || o.labtestgroup, '"'::text, '' ...

Is there a way for me to retrieve the element that is linked to the ng-disabled attribute?

Is there a way to access the element with the ng-disabled attribute inside the function without passing it as a parameter? Here is the HTML element: <input class="needsDisabling" ng-disabled="isFieldDisabled()" type="text"> The isFieldDisabled fu ...

How to Retrieve Upload Progress via HTTP Request in PHP

Is there a way to monitor the progress of file uploads by accessing the HTTP request in PHP? If so, how can this be achieved when uploading files into a MySQL database? require('../connect_db.php'); //Collect all necessary data $name = $dbc-> ...

Creating a basic C++ program using Java concepts (Abstract class)

Java Programming Example (Successful) Define an abstract class Personnell with Manager and Worker as its subclasses. The class contains the abstract function getAnnualIncome(). Personnell employee[] = { new Manager("Thomas", "Nasa", 1337, 250000), ...