I aim to continuously refresh a dynamic canvas line chart with JSON data

Having trouble with my code - the chart isn't updating. I'm new to using canvasJS charts and could use some help.

<%@ page language=”java” contentType=”text/html; charset=UTF-8″ pageEncoding=”UTF-8″%>
<%@ page import=”java.util.*” %>

<!DOCTYPE HTML>
<html>

<head>
  <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
  <script src=”https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
  <script src=”https://canvasjs.com/assets/script/canvasjs.min.js”></script>
  <!-- JavaScript code for fetching data and rendering the chart -->

My JSON data :

[{
  "creation_time": 1564828719000,
  "id": 18443,
  "action": "",
  "com_Z_Axis": "-29.0",
  "humi": "84.4",
  "com_X_Axis": "-27.0",
  "com_Y_Axis": "0.0",
  "pressure": "989.3",
  "gyro_Y_Axis": "0.0",
  "acc_Y_Axis": "0.0",
  "pitch_X_Axis": "351.0",
  "temp": "24.5",
  "yaw_Z_Axis": "191.0",
  "gyro_Z_Axis": "0.0",
  "acc_Z_Axis": "1.0",
  "gyro_X_Axis": "-0.0",
  "acc_X_Axis": "0.0",
  "stability": "stable",
  "roll_Y_Axis": "6.0",
  "direction": ""
}]

Answer №1

setTimeout method is responsible for calling a function or evaluating an expression after a specific number of milliseconds (once), while the setInterval method does the same at specified intervals in milliseconds. In this scenario, switching from setTimeout to setInterval should function correctly.

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
    <script src='https://canvasjs.com/assets/script/canvasjs.min.js'></script>
    <script type='text/javascript'>
      var dataPoints = [];
      var chart;
      $.getJSON('https://api.myjson.com/bins/sysrl', function(data) {
        $.each(data, function(key, value) {
          dataPoints.push({
            x: (value)['creation_time'],
            y: Number(value['temp'])
          });
        }); chart = new CanvasJS.Chart('chartContainer', {
          title: {
            text: 'Live Chart with dataPoints from External JSON'
          },
          zoomEnabled: true,
          axisX: {
            scaleBreaks: {
              autoCalculate: true,
              maxNumberOfAutoBreaks: 5,
              collapsibleThreshold: '15 % '
            },
          },
          zoomType: 'xy',
          //backgroundColor: '#bdcfed',
          animationEnabled: true,
          animationDuration: 5000,
          exportEnabled: true,
          data: [{
            showInLegend: true,
            legendText: 'Temperature',
            markerType: 'circle',
            markerSize: '3',
            markerColor: 'red',
            xValueType: 'dateTime',
            xValueFormatString: 'YYYY - MM - DD HH: mm: ss',
            toolTipContent: 'x: {x}, y: {y}',
            type: 'line',
            dataPoints: dataPoints,
          }]
        }); chart.render(); updateChart();
      });

      function updateChart() {
        $.getJSON('https://api.myjson.com/bins/sysrl', function(data) {
          dataPoints = []; $.each(data, function(key, value) {
            dataPoints.push({
              x: (value['creation_time']),
              y: Number(value['temp']),

            });
          });
        });
      }

      setInterval(function() {
        updateChart()
      }, 1000);
    </script>
  </head>

  <body>
    <div id='chartContainer' style='height: 360px; width: 100%;'></div>
  </body>
</html>

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

React and Material UI: troubleshooting problems with layout columns

I'm working on a project with three columns and I want to include a column for removing each row. Is it possible to add a "removing" column on the right? If so, how can I go about doing it? VIEW CODESANDBOX: HERE const CustomTableRow = ({ row, index ...

Looking for assistance with jqGrid

Is there a method to confirm if the grid has finished loading using a separate function? My goal is to automatically click on the first row and move that row to the second grid once this action occurs. jQuery("#search_grid").jqGrid('setGridParam&apo ...

The response from AngularJS $resource can be considered as both an array and an object

Recently, I obtained this JSON file: [ { "name": "paprika", "imgSrc": "img/paprika.jpg" }, { "name": "kurkku", "imgSrc": "img/kurkku.jpg" }, { "name": "porkkana", "imgSrc": "img/porkkana.jpg" }, { "name": "lehtisalaatti", " ...

Is there a way to adjust the quantity of items in the shopping cart without the need to reload the webpage?

Currently, I am working on a test project using React & Redux. The project involves implementing a basket feature where I receive an array of products structured like this: products: [ { name: "Product one", count: 1, ...

Can someone help me figure out the issue with my Angularjs ng-repeat implementation?

After spending hours trying to figure out why something so simple is not working, I'm at a loss. Testing with a dummy list proves the functionality works, but when I connect my server-side data source, it fails. The JSON returned from the AJAX call i ...

Spring Boot's global exception handler fails to catch HttpMessageNotReadableException

My exception handler successfully captures exceptions thrown from my controller, service layer, or repository layer. However, it fails to catch exceptions occurring before entering the controller. Specifically, when a malformed JSON body is passed to a POS ...

What is the best practice for adding a DOM element at a precise location within an ng-repeat loop?

I am currently working on developing a podcast player application using AngularJS. At this point, I have successfully created a list of available podcasts that can be played, utilizing ng-repeat. The code for the list is shown below: <ul ng-controller ...

What is the best way to access form data in React using a React.FormEvent<HTMLFormElement>?

I am looking for a way to retrieve the values entered in a <form> element when a user submits the form. I want to avoid using an onChange listener and storing the values in the state. Is there a different approach I can take? login.tsx ... interfa ...

Generating and consuming XML data with swagger-node

As a newcomer to swagger-node (swagger-spec 2.0), I am looking to have my API consume and produce both XML and JSON as requested by the customer. Currently, I have only focused on the "producing" aspect of it. When it comes to producing a response, I am a ...

Troubleshooting Browser Behavior: Back Button Not Loading Page - jQuery and HTML5

I've built a dynamic slideshow using jQuery to change images with seamless transitions. To enhance user experience, I'm also updating the page title and URL without triggering a page reload. The code snippet below illustrates how I achieve this: ...

How to retrieve JSON data from unidentified objects using JQuery

I have made an AJAX call and received a JSON file as the response: [ { "LINKNAME": "Annual Training", "HITS": 1 }, { "LINKNAME": "In Focus Newsletter", "HITS": 1 }, { "LINKNAME": "NITA (secured)" ...

Modify the file format depending on the browser being used as Internet Explorer

Currently seeking the most effective method to dynamically alter the file extension of certain images (from .svg to .png) specifically for Internet Explorer users. Uncertain about the optimal approach: consider parsing the HTML code with PHP utilize jQu ...

What is the best way to transition all elements down while sliding a header up or down?

Is it possible to bring down the entire page when hovering over a header element using CSS, ensuring that the header overlaps nothing else on the page? If so, how can this be achieved? See an example of the header in action here: Thank you! ...

Accordions housing Bootstrap 3 pills in a sleek design

I'm working on integrating pills and an accordion in Bootstrap 3. Everything seems to be functioning correctly, but there are a couple of issues I am encountering: When the accordion is open, clicking on another tab closes the accordion. I would li ...

The tagging feature in ui-select isn't working properly, showing an error message that says "Cannot read property 'length' of undefined"

Looking to set up a ui-select for keyword tagging. Initially, when adding a new tag everything works fine, but after removing all tags and adding a new one, I get the error: Cannot read property 'indexOf' of undefined Check out the demo here ...

Parse JSON array into Go struct when the array is embedded within the JSON string

I’m a beginner in Go and currently working with a weather API. I have encountered an issue with unmarshalling the JSON data. The problem seems to be related to having an array within the JSON string structure, which is causing difficulties in defining ...

How can you set a $_GET variable without having to reload the page?

I have a table on my website that displays values for each row, and here's an example code snippet: //JAVASCRIPT <tr onclick="window.history.replaceState(null, null, 'myPage.php?ID=2');"> The URL changes with this code, but it doesn& ...

I keep encountering the issue where I receive the message "Unable to access property 'innerText' of an undefined element" when running the Array forEach function. This problem seems to be happening within the HTMLInputElement section of the code

I am facing an issue where the error occurs because "cardTxt" is not recognized as a string. I verified this using typeof syntax, but I'm unable to understand why it can't be a string. This code snippet includes the use of bootstrap for styling. ...

Combining two JSON objects into one

I have two JSON files: one is a base file and the other contains the same properties but with different values. I want to merge these two objects together. For instance: { a:{ b:"asda" } c: "asdasd" } And the second file: { a:{ b:"d" } ...

Unexpected Timed Out error from Socket.IO adapter when MongoDB connection is lost

I have been experimenting with capturing the disconnection event in mongodb. Everything is working smoothly with this setup: simple.js 'use strict'; var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:2701 ...