Add the text received from the Ajax request to an array specifically designed for AmCharts

Hello, I'm new to JavaScript and seeking assistance. My goal is to create a chart with real-time data from my MCU, but I'm unsure about pushing a string into an array. Currently, the Array (chart.dataProvider) in this code remains undefined.

var chart = AmCharts.makeChart("chartdiv",{

...

"dataProvider":[],
});

function f() { 
     var req = new XMLHttpRequest();
     req.onreadystatechange = function() {
     if (this.readyState == 4 && this.status == 200) {
     var value = this.responseText;            
     //  value= {cat: 1, c1: 2, c2: 3};    
     alert(value); //output: {cat: 1, c1: 2, c2: 3}
     chart.dataProvider.push(value);
     chart.validateData();
                                                      }};
     req.open("GET", "http://", true);
     req.send();
     }

This method also works:

chart.dataProvider.push({ cat: 1, c1: 2, c2: 3 });

However, how can I push data using XMLHttpRequest?

Answer №1

Make sure to set the initial value of chart.dataProvider to an empty array [] before adding new data.

If you encounter any issues, you can also add a condition to check if it's undefined and initialize it accordingly like this:

chart.dataProvider = chart.dataProvider ? chart.dataProvider : [];

Additionally, if you are dealing with asynchronous operations like ajax, consider using Promises or callbacks to ensure that the push operation is done at the right time.

I hope these suggestions help resolve your question.

Answer №2

Hey everyone, I stumbled upon a really simple solution:

let data = this.responseText;
alert (data);   // output: 1category500fColumn1000sColumn
let category = data.substring(0, data.indexOf('category'));
let firstColumn = data.substring(data.indexOf('category')+8, data.indexOf('fColumn'));
let secondColumn = data.substring(data.indexOf('fColumn')+7, data.indexOf('sColumn'));
     chart.dataProvider.push({
     cat: category,
     c1: firstColumn,
     c2: secondColumn});

It should look something like this:

        {cat: 1,
         c1: 500,
         c2: 1000}

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

Automatic Expansion Feature for HTML Tables

http://jsfiddle.net/bzL7p87k/ In my table, placeholders are filled with special words. However, what happens when I have more than 4 rows? For instance, if there are 21 placeholders for 21 rows? What I mean is this: I only have one row with a placeholder ...

Issue with Highcharts: The useHTML flag is not functioning properly when trying to render labels

Currently, I am utilizing highcharts and a phantomjs server for rendering charts and labels. However, I have encountered an issue where the useHTML flag does not function as expected when rendering the labels. Following the instructions in the documentatio ...

Vue-incredible swiper, a pair of components swipe using buttons adjacent to one another

I am currently using vue-awesome-swiper and encountering an issue. The swipers on my page have buttons (prev slide, next slide) for navigating through slides. However, when I include two swipers on the same page, the buttons of one swiper end up affecting ...

An error occurs when using e.slice function

I am facing an issue with my kendoDropDownList that uses kendo UI and jQuery. I cannot figure out why this error is occurring. $("#drpState").kendoDropDownList({ optionLabel: "States...", delay: 10, ...

What is the best choice for code design patterns in a nodejs environment? What are the key considerations for creating a well-

Although I have a background in games development using C/C++/C#, I have recently delved into automated testing and now I am eager to learn more about backend development. My current project involves creating a platform for automated backups, building fr ...

The operation of my NodeJS application suddenly halts

In my project, I have a Server.js file that I run from the command line using: node server Within the Server.js file, a new instance of class A is created Class A then creates instances of both class B (web socket) and class C (REST API) If the web socket ...

The result of Ajax is coming back as unclear

I've encountered an issue while trying to upload an image to my server using a POST form and AJAX. Every time I submit the form, my AJAX response shows as undefined in the error box. Here is the Ajax function I am referring to: $('.register_subm ...

The error message "gulp error - _.flattenDeep is not a function when using gulp.watch" is indicating

Whenever I run a watch task, why am I encountering the TypeError: _.flattenDeep is not a function error? Below is the content of my gulpfile.js : var gulp = require('gulp'); var sass = require('gulp-sass'); var sourcemaps = require(&a ...

How to fetch an image from a web API using JavaScript

I have recently entered the world of web development and I am facing an issue where I am trying to retrieve a Bitmap Value from a web api in order to display it on an HTML page using JavaScript. However, despite my efforts, the image is not getting display ...

The Angular UI Bootstrap Datepicker fails to appear on top of the Bootstrap Modal

I'm currently working on an Angular app that utilizes UI Bootstrap. Within my app, I have a modal containing a Datepicker at the bottom. However, I've encountered an issue where the Datepicker remains confined within the modal when expanded. I at ...

loading preloaded fonts at the optimal moment

My webfonts are loaded using Webfontloader as shown below: <script src="//ajax.googleapis.com/ajax/libs/webfont/1.5.10/webfont.js"></script> <script> WebFont.load({ custom: { families: ['BlenderProBook' ...

ScriptSharp - submitting information in a key-value pair format

Currently, I am attempting to send data using Script# by utilizing the jQuery.AjaxRequest method: jQueryAjaxOptions options = new jQueryAjaxOptions(); options.Url = "/Server/Login.ashx"; options.Data = new LoginRequest(username, password); jQuery.AjaxRequ ...

What is the best way to appropriately update a partial that displays another partial (refreshing with JavaScript leads to a page within a page)?

Update 2 - marzapower's assistance proved valuable once again. The success section in the ajax was identified as the root cause of the issue, as explained below. UPDATE: marzapower's solution works effectively (refer to it below), but I require ...

The useRef() hook call in NextJs is deemed invalid

I have been attempting to implement the useRef() hook within a function component in my NextJs project, but I keep encountering the error below. Despite reviewing the React Hook guidelines, I am unable to determine why this error persists and the functio ...

What is the best way to show the user's name on every page of my website?

I'm facing an issue where I can successfully capture the username on the home page using ejs after a login, but when transitioning to other pages from the home page, the username is no longer visible. It seems like I am missing some logic on how to ha ...

The close menu button is not functioning properly when clicked outside the menu - the buttonevent.matches is not recognized as a

I am encountering an issue with the dropdown menu that is not closing when clicking outside of the menu button. Despite having faced this problem before, I can't seem to find a solution now. Any help would be greatly appreciated as I am uncertain why ...

retrieve PHP function calls as an array using Ajax

While working in PHP, I have encountered a situation where I needed to call a PHP function using AJAX: <button onclick="loop()">Do It</button> function loop() { $.get("ajax.php", { action: "true" }, function(result) { $("in ...

Using AngularJS to bind radio buttons to ng-model

Here is a snippet of my HTML code where I attempted to bind the "formFriendsAll" scope to the ng-model. <form ng-submit="submitForm()" > <div class="col-sm-3"> <div class="form-group"> <label>Which Persons to show?< ...

When a block is clicked, jQuery will reveal that block while hiding the others sequentially, starting with the second block, then the third, and finally the fourth

Creating a navigation menu with 4 blocks can be a bit tricky, especially when trying to show one block at a time upon click. Here is my code attempt, but unfortunately it's not working as expected. I would greatly appreciate any help or suggestions on ...

Utilizing Ajax to Populate a Dropdown List with Data

Currently, I am retrieving data from an API. The data consists of IDs and charity names that need to be displayed in a dropdown list. While I have successfully shown the charity names in the dropdown list, I am struggling with including the IDs. How can I ...