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

Is JavaScript responsible for creating threads for non-blocking AJAX requests?

It is widely believed that JavaScript operates on a single-threaded model, but it has the ability to run asynchronously. One intriguing aspect is how this single-threaded model manages non-blocking AJAX requests. Consider a scenario where a non-blocking A ...

Incorporating interactive maps into an AngularJS web application

I've been attempting to integrate Google Maps into my AngularJS application, using the script tag below: <script src="https://maps.googleapis.com/maps/api/js?key=[MySecretKeyHere]&callback=initMap" async defer></script> I found this ...

What is the process for including JSON data in an ArrayList?

Hello everyone! I'm fairly new to this industry and recently made a REST request for a project. Here is the response that I received: {"success":true,"timestamp":1524649444,"base":"EUR","date":"2018-04-25","rates":{"AED":4.486623,"AFN":85.583411,"ALL ...

submit the contact form information to both the database and email for further processing and storage

Currently, I have the code for connecting to a database and mail.php. I am able to save contact form data in the database successfully, but I also want to send an email to my address which I'm unsure how to do with manage_comments.php. Here are the ...

Attempting to change JSON into a dictionary format using Python

I tried extracting JSON data from a website using the application/ld+json, but I am facing issues converting the string to a Python dictionary. When running the code in the terminal, I encountered an error stating JSONDecodeError("Expecting value", s, err. ...

issue with data binding in ons-dialog

Utilizing an ons-dialog to display a popup prompting the user to sign up for a newsletter. I have set a 3-second timeout to prevent users from immediately closing the prompt without reading it or waiting. I aim to initially show the dialog with the ' ...

The standard date format used in Javascript/Jquery programs

I have a kendo date picker set to display dates in the format "MM/dd/yyyy". I need to use jquery or javascript to ensure that the selected date is not in the future and is greater than '01/01/1900'. The problem I'm encountering is handling ...

Material-UI and TypeScript are having trouble finding a compatible overload for this function call

Currently, I'm in the process of converting a JavaScript component that utilizes Material-ui to TypeScript, and I've encountered an issue. Specifically, when rendering a tile-like image where the component prop was overridden along with an additi ...

How can I choose a JToken using JSONPath when there are multiple possible name options to consider?

I have a JSON object structured like this: { category1: { items [ ... ] } } It could also be represented as: { category2: { items [ ... ] } } My goal is to extract the JArray of items using a single JSONPath. Is there a ...

URL not functioning properly on Django CMS menu

After setting up django-cms and creating a collapsible menu with categories and subcategories, I encountered an issue. When clicking on a main category, the URL appears correct but it does not navigate to the corresponding page. Main categories without chi ...

Error: The 'book' property is undefined and cannot be read in the BookDetails.render function

I am currently working on retrieving data from renderList and implementing it in render(). Upon using console.log this.renderList() https://i.stack.imgur.com/IwOzw.png The retrieved data is displayed above. While working on the render(), I attempted ...

Utilizing AngularJS to iterate through an array of dictionaries

Within a specific section of my HTML code, I am initializing a scope variable like this: $scope.my_data = [ { c1: "r1c1", c2: "r1c2", c3: "r1c3", ...

When the mouse hovers over the slider, the final image jumps into view

After successfully building an image slider that displays 2 partial images and 1 full image on hover, I encountered a bug when setting the last image to its full width by default. This caused a temporary gap in the slider as the other images were hovered o ...

Preventing Redundancy in Angular 2: Tips for Avoiding Duplicate Methods

Is there a way I can streamline my if/else statement to avoid code repetition in my header component? Take a look at the example below: export class HeaderMainComponent { logoAlt = 'We Craft beautiful websites'; // Logo alt and title texts @Vie ...

In the event that the "li" element contains an "

<ul> <li> <ul></ul> </li> <li></li> <li></li> <li></li> <li> <ul></ul> </li> </ul> Is there a way to specifically a ...

What is the proper way to activate speech recognition on electron?

I have a chatbot application running on Electron, and I am in need of implementing speech-to-text functionality. I initially tried using window.SpeechRecognition and window.webkitSpeechRecognition, but it seems like Chrome does not support speech recogniti ...

Is it correct to use React Router's useNavigate with a useEffect hook for navigation?

I am a beginner to React and I have been working on creating a loading/greeting page that automatically navigates to the next page after a few seconds. In React Router v6, there is a useful hook called useNavigate() which allows you to control navigation. ...

Transform an array of objects into a nested tree structure with Javascript

I am currently facing a challenge with handling a complex json file using javascript to structure it hierarchically. My goal is to convert an array of objects into a deeply nested array, where there can be multiple divNames with varying categories and subc ...

Dealing with the challenge of managing multiple instances in a setup involving Ajax long polling (comet) and PHP on Lighttpd v1

I am a newcomer to this platform, so I hope to provide all the necessary details about my question. I have been attempting to set up a mechanism for "new message arrived notification" using long polling. Currently, I am triggering the polling request thro ...

Issues with parsing JSON data in Swift's Data structure are causing challenges

I am currently attempting to extract information from the YouTube Data API and convert it into a string using Swift. To achieve this, I am utilizing Alamofire along with SwiftyJSON. However, when attempting to parse the data, SwiftyJSON fails to do so, res ...