Utilizing AJAX in Cordova to Generate Dynamic JavaScript Charts from JSON Data

Exploring the world of Cordova, I have delved into utilizing canvas Js for visualizing data in chart format. Following a helpful tutorial, I created a Json file and inserted the specified data as instructed, following each step diligently. The outcome matched the expected results showcased in the image below:

https://i.sstatic.net/KsV5t.png

Now, my aim is to incorporate datetime values on the xAxis. Referring to this enlightening tutorial, successfully integrated datetime values on the xAxis as depicted in the image below:

https://i.sstatic.net/7yiad.png

However, upon attempting to include the same datetime format in my json and visualizing it on the chart, encountered an issue where the chart appeared empty. Below showcases the content of my json data:

[
  [ 1088620200000, 71 ],
  [ 1104517800000, 65 ],
  [ 1112293800000, 72 ],
  [ 1136053800000, 52 ],
  [ 1157049000000, 49 ],
  [ 1162319400000, 62 ],
  [ 1180636200000, 78 ],
  [ 1193855400000, 55 ],
  [ 1209580200000, 22 ],
  [ 1230748200000, 65 ],
  [ 1241116200000, 100 ],
  [ 1262284200000, 58 ],
  [ 1272652200000, 74 ],
  [ 1291141800000, 79 ],
  [ 1304188200000, 58 ]
]

Provided below is my snippet of javascript code:

$(window).on('load', function () {
        var dataPoints = [];
        $.getJSON("data.json", function (data) {
            $.each(data, function (key, value) {
                dataPoints.push({ x: value[0], y: parseInt(value[1]) })
            });
        });
        var chart = new CanvasJS.Chart("container", {
            zoomEnabled: true,
            zoomType: "xy",
            animationEnabled: true,
            animationDuration: 2000,
            exportEnabled: true,

            title: {
                text: "Energy vs Date Time"
            },
            axisY: {
                title: "EnergykWh",
                interlacedColor: "#F8F1E4",
                tickLength: 10,
                suffix: "k",
            },
            data: [
                {
                    type: 'column',
                    xValueType: "dateTime",
                    showInLegend: true,
                    name: "series1",
                    legendText: "EnergykWh",
                    dataPoints: dataPoints
                }
            ]
        });

        chart.render();
    });

In the aforementioned code, there exists a commented-out section within dataPoints that mirrors the data structure present in my Json. Removing the comments reveals the data on the chart correctly. However, when attempting to fetch the data from the json file, nothing appears on the chart.

It seems like something crucial is missing; any assistance or advice on resolving this issue would be greatly valued.

Answer №1

If you want to easily store JSON data and display it in a chart on your HTML page, one method is to save the JSON data into a JavaScript file by assigning it to a variable. You can then include this JavaScript file in your HTML page and use a for loop to extract the data and present it in the form of charts. Check out the code below for a better understanding.

Save the JSON data into a JavaScript file

var jsonData = [{ "x": "2016-06-25 12:58:52", "y": 10.22 }, { "x": "2016-14-25 14:42:47", "y": 24.73 },
            { "x": "2016-07-25 13:33:23", "y": 11.14 }, { "x": "2016-15-25 15:07:26", "y": 26.58 },
            { "x": "2016-08-25 13:49:18", "y": 13.58 }, { "x": "2016-16-25 15:14:49", "y": 27.66 },
            { "x": "2016-09-25 13:55:01", "y": 15.25 }, { "x": "2016-17-25 15:32:51", "y": 28.68 },
            { "x": "2016-10-25 14:00:15", "y": 17.25 }, { "x": "2016-18-25 15:40:32", "y": 30.73 },
            { "x": "2016-11-25 14:23:31", "y": 19.99 }, { "x": "2016-19-25 15:58:07", "y": 32.46 },
            { "x": "2016-12-25 14:30:36", "y": 21.78 }, { "x": "2016-20-25 16:21:25", "y": 34.79 },
            { "x": "2016-13-25 14:34:23", "y": 23.45 }];

Include your JavaScript file in HTML page

<script type="text/javascript" src="scripts/json.js"></script>

Use a for loop to retrieve x and y data

for (var i = 0; i < jsonData.length; i++) {
           dataPoints.push({
              x: new Date(jsonData[i].x),
              y: jsonData[i].y
          });
        }

Pass these dataPoints to CanvasJS

     data: [
            {
                type: 'column',
                xValueType: "dateTime",// no use for it
                //xValueFormat: "YYYY-MM-DD",// use xValueFormat 
                showInLegend: true,
                name: "series1",
                legendText: "EnergykWh",
                dataPoints: dataPoints

            }
        ]

I hope this method works effectively for your project.

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

Error interpreting the response string

After attempting to extract values from a response by parsing it into separate strings, I encountered some difficulties. The response text looks like this: response = "Data1{ key1='4722**********6', key2='2107', ...

How to retrieve the clicked value using jQuery within a jinja2 loop

I'm currently working on an app that utilizes a Flask backend and Jinja2 templating. Within the HTML, I have a loop set up to organize data into batches, creating three columns on the web page: {% for batch in df.iterrows() | batch(3) %} <d ...

"Dealing with Time Out Issues in Android's JSON HTTP Request Connection

How can I handle a Connection Timeout when making an httpRequest in my application? When the connection is blocked by a firewall and there is a delay in connecting to the server, I want to return to the previous activity and display a Toast message indicat ...

Error encountered with Next.js and Square API: The Fetch API cannot load due to the unsupported URL scheme "webpack-internal"

I encountered an issue while attempting to retrieve stock data from the Square API. injectGlobalHook.js:1648 Fetch API cannot load webpack-internal:///./node_modules/@next/react-dev-overlay/lib/internal/ReactDevOverlay.js. URL scheme "webpack-internal ...

Creating HTML form input fields for reading and writing an XML file

Currently working on constructing an HTML form containing input fields to read and modify data from an XML file. The initial task involves loading values into the input fields upon page load, but unfortunately, it is not functioning as expected. < ...

Creating a dynamically sorting page for displaying products by utilizing a combination of PHP, AJAX, jQuery, and a dropdown menu

I'm currently working on implementing a dropdown menu that allows users to sort a page by "price high-low" or "price low-high". Below is the HTML code with an ID of "show_product": <div class="row" id ="notification-bar"></div> <div c ...

What is the best way to integrate ES6 ReactJS code into an Express application?

I am trying to initially render my ReactJS application on the server using ExpressJS. Although I have been able to import ES6 modules using require(), the module crashes upon loading because it contains ES6 code (ES6 import and export). Index Route var ...

Traverse through the loop with React Material UI in JavaScript

Hi everyone, I'm having trouble with this code. I want to iterate through an object called paleogenome.data and create a CardHeader for each item: { Object.keys(paleogenome.data).forEach(function (key){ console.log(paleogenome.data[key] ...

Creating a 404 Error Response in Express.js

Inside app.js, I currently have the following code: // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); This code executes when a non-existent URL ...

Activate the saturation toggle when a key is pressed in JavaScript

I am trying to modify a script that currently toggles the value of a variable when a key is pressed and then lifted. Instead of changing the variable value, I would like to adjust the saturation of the screen based on key presses and releases. How can I ac ...

Leveraging JSON in Play 2

Currently, I am working on developing a straightforward application that allows me to manage different users by creating, reading, updating, and deleting their information. Initially, I set up a basic UI-based view, controller, and model which are function ...

Optimal method for Python to engage with MySQL databases

As a beginner in programming, I am currently teaching myself the correct ways of coding. My current project involves writing a script in Python that will receive 1-3 values every second and save them to a MySQL database. Eventually, I plan on creating a we ...

An issue arose during the page prerendering process for "/" on Vercel | Next.js resulting in a deployment error

When attempting to deploy my website using Vercel and generating static pages, I encountered the following error in the logs: info - Generating static pages (0/6) Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/ ...

The internet browser encountered a JavaScript runtime error (0x800a138f) in which it was unable to retrieve property '0' due to it being either undefined or pointing to a

I'm encountering an issue with my javascript/jquery function that retrieves the selected dropdown value. Everything works fine in Chrome, but when I try to run my application in IE, it throws an error. $("#Application_AppCountries").change(function ( ...

How can an Ajax accordion panel be expanded in the event of failure during required field validation?

When using the 2nd and 3rd panels of an ajax accordion, I have set focus on my required field validator but the correct panel does not automatically open. Is there a way to make the panel where the next required field is located open automatically? < ...

How to assign various column values to a PHP array in JSON format from a MySQL database

I am struggling with making a JSON Ajax request and receiving an array in return. After browsing through multiple questions, I came across this code snippet that I edited to fit my problem: var hej[]; function ajax_search(){ $.getJSON('test.php ...

Building JSON request bodies in Python

I'm currently facing a challenge in formulating a JSON body for a POST request. A scenario where the body is rigidly defined like so: body_works = {"databaseName": "admin", "username": "foo", "password&quo ...

Sending information from the client to the server using AJAX in conjunction with a

My apologies in advance if my English is not perfect. I am currently facing issues with sending data to my ExportServlet using ajax. ExportServlet.java public class ExportServlet extends HttpServlet { private static final long serialVersionUID = 67156058 ...

Changing json into another format

I am struggling with a JSON data format issue. I have tried using Object.values and object.keys along with Array.prototype.map(), but my algorithm is not producing the desired outcome. [ { "2018-01-01": [ { "firstname": "mati", "lastname": "mati ...

What is the method for displaying a div adjacent to a password input field?

I am attempting to display a password verification box next to an input field. The current logic is functioning properly, but the box containing all password requirements is not appearing in the correct position. Instead of being positioned adjacent to the ...