Adjustable Title in Line Plot

After receiving a JSON object from a web server in response, I am encountering some challenges with extracting and displaying the data. The JSON array consists of monthly key-value pairs like {"JAN":"17"}, {"FEB":"19"}, {"MAR":"21"}, etc.

To display these keys dynamically on the x-axis of a chart, I have attempted to extract the keys into an array using JavaScript. However, my current approach doesn't seem to be working as expected.

var al_key = [];

//For loop for x axis dispaly.
alert("al_key.length --------->"+al_key.length);

var jsonObj = []; //declare array

for (var i = 0; i < al_key.length; i++) {
    jsonObj.push({value: i, text: al_key[i].value});
}

// Add axes
chart.addAxis("x", {min:1, max: 12 ,labels: jsonObj , fixLower: "major", microTicks: true, majorTickStep: 1});  

chart.addAxis("y", { min: 0, max: 50, vertical: true, fixLower: "major", fixUpper: "major", includeZero: true });

I'm seeking advice on where I might be going wrong in this process or if there are alternative methods to achieve the desired result of dynamically displaying months on the x-axis. Any suggestions or help would be greatly appreciated.


Additional Response:

Recently, when dealing with a JSONArray object containing single JSONObjects, I ran into some issues while trying to access and manipulate the data present within it.

To provide an example scenario, consider the following code snippet showcasing server-side coding:

JSONObject object=new JSONObject(); 
object.put("JAN":"17"); 
object.put("FEB":"19"); 
object.put("MAR":"21"); 
object.put("APR":"23"); 
object.put("MAY":"24"); 
object.put("JUN":"27");

JSONArray arrayObj=new JSONArray(); 
arrayObj.add(object);

System.out.println(arrayObj); // Output: {"JAN":"17"},{"FEB":"19"},{"MAR":"21"},{"APR":"23"},{"MAY":"24"},{"JUN":"27"}];

In a JSP context, further actions need to be taken such as fetching desired values from the database and handling responses accordingly:

//Call to the database to fetch the desired value 
dojo.xhrGet( { url : "/POC/Action.do", 
               handleAs : "json", 
               sync: true, 
               load : function(response, ioArgs) { 
  alert("retrived response ------"+response); 
  for(var i in response) 
    for(var x in response[i]) 
      output.push(response[i][x]); 
  alert("Get value to draw line chart---------------------->"+output); 
},
error: function(response, ioArgs){ 
  dojo.byId("grid").innerHTML = "An error occurred, with response: " + response; 
  return response; 
}, 
handleAs: "json" });

The objective here is to extract keys from the response object and prepare them in a format suitable for displaying on the x-axis of a chart. If any insights or recommendations can be provided regarding this process, please feel free to share your thoughts.

Answer №1

Regarding the updated information you provided:

To optimize how the JSON is sent (assuming a Java servlet using the org.jon package), consider the following code snippet:

JSONArray array = new JSONArray();
arrayObj.put(new JSONObject("{'month':'JAN', 'value':'17'}");
// Repeat this for the remaining data

You can utilize this in your dojo chart, as shown below with jsonObj3.


Original comment.

Refer to examples at this link, particularly the section:

labels: [{value: 0, text: "zero"},
         {value: 2, text: "two"},
         {value: 4, text: "four"} 

Additionally, incorporate two series:

addSeries("Series A", [1, 2, 3, 4, 5], {stroke: {color: "red"}, fill: "lightpink"}).
addSeries("Series B", [5, 4, 3, 2, 1], {stroke: {color: "blue"}, fill: "lightblue"}).

For the series, consider structuring the JSON like this:

var months = ["JUL","AUG","SEP","OCT","NOV","DEC","JAN","FEB","MAR","APR","MAY","JUN"];
var jsonObj2 = [];

for (var i = 0; i < months.length ; i++) {
    jsonObj2.push({value: i, text: months[i]});
}

If you prefer a single JSON object, format it in the following way:

var data = [{month: "JUL", value:"5"},
            {month: "AUG", value:"7"},
            {month: "SEP", value:"9"},
            {month: "OCT", value:"11"},
            {month: "NOV", value:"13"},    
            {month: "DEC", value:"15"},
            {month: "JAN", value:"17"},
            {month: "FEB", value:"19"},
            {month: "MAR", value:"21"},
            {month: "APR", value:"23"},
            {month: "MAY", value:"25"},
            {month: "JUN", value:"27"}];

var jsonObj3 = [];

for (var i = 0; i < data.length ; i++) {
    jsonObj3.push({value: i, text: data[i].month});
}

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

Issue 500 encountered while implementing VB.NET with jQuery AJAX

Having trouble populating a select option using jQuery ajax, and I could really use some assistance! Encountering the following error: Failed to load resource: the server responded with a status of 500 (Internal Server Error) http://localhost:20440/admin ...

Node.JS function using try catch block

Is the following function suitable for use with Async Node.JS? I am wondering if it is written correctly, whether errors will be handled properly, or if it has been incorrectly implemented in terms of Async Node.JS. If there are issues with the implemen ...

Navigating through various JSON arrays using Angular

I am currently working with a large JSON file in Angular and trying to iterate through it. The structure of the JSON file is as follows: { "subject1":[ { "title":"titlehere", "info":"infohere." }], ...

receiving a parsererror due to an assumed lack of data in the JSON

THE ISSUE My JSON data contains associative arrays that I extract and display on my webpage. Occasionally, one or more of the sub-arrays may be empty as part of normal operation. However, whenever an empty sub-array is encountered, it triggers a "parserer ...

Need help accessing data from an API using Axios.post and passing an ID?

Can someone help me with passing the ID of each item using Axios.Post in order to display its data on a single page? The image below in my Postman shows how I need to send the ID along with the request. Additionally, I have the first two URL requests for t ...

Implementing asynchronous validation in Angular 2

Recently started working with Angular 2 and encountered an issue while trying to validate an email address from the server This is the form structure I have implemented: this.userform = this._formbuilder.group({ email: ['', [Validators.requir ...

The method firebaseApp.auth does not exist in user authentication using Firebase

Implementing user authentication with Firebase in my React webapp has been a challenge due to issues with the firebaseAuth.app() function. Despite trying various solutions such as reinstalling firebase dependencies, updating imports to SDK 9 syntax, and ad ...

Fixed navigation menu at the top of the screen

Can anyone help me with my navbar issue? I want it to stay on top of the page, but there's a huge gap between the top of the page and the nav bar. I've tried running a JS file, but it doesn't seem to fix the problem. Any ideas on how to make ...

Tips for adding an array to an array of objects with AngularJs

I'm facing an issue with the array structure in my code. Here's what I currently have: $scope.arrayList=[{FirstName:"",LastName:""}]; $scope.Address=[{address:"",PhoneNumber:""}]; What I want to achieve is to push the $scope.Address array into ...

What is the process for adding new data to a data source without overwriting existing information?

I need assistance with a react native app I am developing. I am currently facing an issue where the data received from a fetch request needs to be displayed in a list view. However, each time new data is fetched, it overwrites the previously received data ...

Calling functions by name in Java using JSON objects

Is it possible to invoke a function from a Java JSON object? For example: In Java: JSONObject json = new JSONObject(); json.put("fnRowCallback", "test()"); Using jQuery: $ (function () { "use strict"; function test() { alert('test ...

"Utilizing React.js to implement white-space styling on numeric values for

I am a beginner in Reactjs and eager to learn and improve. Here is some code I have been working on: there's an <h1> element with the text "test", and beneath it, I want to display numbers vertically like this: 1:1, 1:2, 1:3. However, the CSS do ...

How to have multiple versions of grunt coexisting on a single machine

I am involved in two different projects that have unique requirements for Grunt versions: Project A specifically needs Grunt v0.3.2 Project B requires Grunt v0.4.1 Both of these projects are managed in separate workspaces. Currently, I have Grunt v0.4. ...

Encountering an error with the package.json file when delivered via N

After developing an NPM package and testing it by installing, I encountered an ENOENT error while trying to install dependencies for GruntJS in a nested node_modules directory using npm install. The steps that led to this error were: npm install pavilio ...

The XMLHttpRequest response states that the preflight request did not meet the access control check requirements

I am attempting to subscribe to a firebase cloud messaging topic by sending an http post request. var data = null; var xhr = new XMLHttpRequest(); xhr.withCredentials = true; xhr.addEventListener("readystatechange", function () { if (this.readyState ...

Angular Circumstance

Can you help me out? I am trying to figure out how to create an IF...ELSE condition using AngularJS on my index.html file: <ons-list-item modifier="chevron" class="list-item-container" ng-repeat="item in categories track by $index"> <a href="#/pa ...

JavaScript function returning code

I am trying to create a JavaScript object with multiple functions, but I keep encountering an exception undefined is not a function Here is my JS code: var Cars = null; $(function () { Cars = function() { return { ...

Leverage HTML within JSON for a multilingual website using i18next with Next.js

I am working on a multi-language website using Next.js. To handle the translations, I am using the package i18next. In my JSX code, I define variables like this: {t("satisfied:title")} This means {t("JSONfileName:JSONvariable")} However, when I try to i ...

Encountered an issue with accessing the property 'path' of undefined in nodejs

Below is my server side code snippet: var fs = require('fs'), MongoClient = require('mongodb').MongoClient, db; var url = "mongodb://localhost:27017/fullwardrobedb"; MongoClient.connect(url, {native_parser: true}, function (err, connec ...

Is there a better way to implement an inArray function in JavaScript than using join and match?

Recently, I created an inArray function for JavaScript which seems to be working fine. It's short and a bit unusual, but I have a nagging feeling that there might be something wrong with it, although I can't quite pinpoint what it is: Array.prot ...