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

Display the webpage exclusively when the application has been set with `app.use('/api')` in Express 4

Here is what I currently have: app.js ... var api = require('./routes/api'); app.use('/', api); app.use('/api', api); ./routes/api ... var router = express.Router(); router.get('/', passport.authenticate(' ...

Having difficulty interpreting the JSON response sent by Google

I've been having trouble parsing a Json response from this specific URL. I've tried using SBJsonParser, MTJSON, and another parser, but unfortunately, all three have returned NULL in my case. apiUrlStr = @"http://maps.google.com/maps?output=drag ...

The dilemma of selecting objects in Three.js

Currently, I am developing a small web application that utilizes three.js. However, I have encountered an issue: I created a prototype with my three.js content and everything functions correctly (the canvas size in the prototype matches the browser window ...

Update the user information quickly

In my Express application, I have implemented several routes and a login function. Each user has a balance associated with their data, which is stored in an 'express-session'. However, when the user refreshes the page, I need the balance to be up ...

The Less compiler (lessc) encounters an issue on a fresh operating system. ([TypeError: undefined is not a function])

After setting up my new development environment on Windows 10, I encountered an issue with less. Following the instructions on lesscss.org, I installed less using: npm install -g less The installation process completed without any errors. However, when ...

Troubleshooting problems with Window.postMessage()

When attempting to fetch data from different domains, I am facing an issue. However, if I run the code on the same server, everything works perfectly fine and I am able to retrieve the message. index.html: <head> <title>Test 1</title&g ...

Jackson encountered difficulty in the conversion of JSON to a list of maps

In my spring-boot application, I have a controller that looks like this: @RequestMapping(path = { "/multiCommunication" }, consumes = { MediaType.APPLICATION_JSON_VALUE }, method = RequestMethod.POST) ResponseEntity<Object> multiCommunicatio ...

What is the best way to extract text from a dynamically changing element using jQuery?

I've been struggling with a coding issue. Despite trying numerous approaches, I keep encountering the same problem where every new button I add ends up having the same text or, alternatively, nothing seems to work as expected. $j serves as my variabl ...

Transforming a malformed JSON string into a List of class objects

I stumbled upon a web service provided by another company that returns JSON data in an unusual format. Here is how the JSON appears: ["TERMINAL_NO","METER_NO","RAMZE_RAYANEH_SHENASE_GHABZ","PARVANDEH_ESHTERAK","POWER_UTILITY","CT_RATIO","PT_RATIO","NAME_ ...

Minify Magic Dreamweaver Plugin

Does anyone know of a plugin that can minify javascript or css files as they are uploaded using Dreamweaver or similar coding software? For example, if I create a file like functions-global.js, the plugin would upload the original file and also generate a ...

Navigating with Vue.js using programmatic methods while passing props

I am working with a Vue component that includes a prop called 'title' like this: <script> export default { props: ['title'], data() { return { } } } </script> After completing a specific action, I need to pro ...

What could be causing the malfunction of Bootstrap Multiselect functionality?

I have been attempting to set up Bootstrap Multiselect but it simply refuses to work. Despite trying various solutions, I am unable to pinpoint the issue. My index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF- ...

Comparison between Enhancing Tomcat in Spring and JUnit Testing Behavior

After encountering difficulties converting JSON into a Java object, I found the solution by upgrading from Spring 3.0.3 to Spring 3.2. The initial issue is detailed here. However, a new problem has arisen - my serialization/deserialization works perfectly ...

Collaborating on user authorization within a MEAN.JS framework

Recently, I decided to dive into the world of web application development by using MEAN.js full stack solution. Using the generators within MEAN.js, I was able to effortlessly create multiple CRUD models along with all the necessary express routes. In ad ...

Exploring the process of iterating through arrays within an object in vue.js using the v-for directive

Is there a way to iterate through an output object using the v-for template in Vue.js? new Vue({ el: app, data: { output: { player: [1, 5, 61, 98, 15, 315, 154, 65], monster: [14, 165, 113, 19, 22], }, }, }); <script src= ...

What is the best way to secure the installation of python packages for long-term use while executing my code within a python shell on NodeJS?

I have been encountering difficulties while attempting to install modules such as cv2 and numpy. Although I have come across a few solutions, each time the shell is used the installation process occurs again, resulting in increased response times. Below i ...

Background image not displaying in new tab after Chrome extension installation

I have been developing a Chrome extension that alters the background image of a new tab. However, I have encountered an issue where the background image doesn't change the first time the extension is loaded. This problem has also occurred very occasi ...

Generate several invoices with just a single click using TypeScript

I'm interested in efficiently printing multiple custom HTML invoices with just one click, similar to this example: Although I attempted to achieve this functionality using the following method, it appears to be incorrect as it prompts the print dialo ...

Having trouble with my Slack Bot development due to an unexpected error

While attempting to create a Slack Bot in Node, I consistently encounter an error when running npm start in my terminal: The error seems to be located in the Vow.js file. Despite double-checking everything, I can't seem to pinpoint the issue. For gui ...

What causes certain files to sporadically duplicate themselves in Visual Studio Code?

While using vscode for NodeJS development, I have noticed that certain files seem to duplicate themselves sporadically. Why is this happening and what steps can I take to resolve it? I am unsure of how to tackle this issue... ...