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

The Bootstrap nav-link class functions perfectly in Firefox, smoothly guiding users to the appropriate section. However, it seems to be experiencing some issues

I am currently working on customizing a one-page web template and I don't have much experience with Bootstrap. The template can be found at . My issue is that the menu items are not functional in Chrome. When I click on any menu item, nothing happens ...

Load the AJAX-enabled guestbook into the designated DIV element

I have been trying to incorporate a dynamic guestbook into my web page using a DIV tag. I attempted to load the guestbook using the following code: $(document).ready(function() { $('.diskusia').click(function () { $("#disk").load("diskusia/index ...

Expanding your JavaScript skills: Tackling nested object key and value replacements

I am looking to manipulate the values of a nested object using JavaScript. The structure of the object is outlined below. let jsonObj = { "service":[ { "name":"restservice", "device&quo ...

Utilize a singular ajax function to handle various events with personalized data parameters

Could someone help me with this specific issue? Here is an explanation. Let's say I have a function called load_window() and various events like clicks, changes, etc. How can I properly create a custom_data variable in these events and use it in the ...

Ways to clear dropdown selection in Vue based on a specific condition?

I am currently developing a dropdown menu for selecting visit status options, which include "pending," "canceled," "rejected," and "approved." In the case of an approved visit status, I would like the dropdown selection to only display the options for "can ...

Is there a way to allow only the block code to shift while keeping the other span tags stationary?

Is it possible to change the text without affecting other span tags in the code? I want to make sure only this specific text is updated. How can I achieve that? var para_values = [ { content: "BRAND " }, { content: "MISSION" } ]; functi ...

Exploring the intricacies of using jquery text() with HTML Entities

I am having difficulty grasping the intricacies of the jquery text() function when used with HTML Entities. It appears that the text() function converts special HTML Entities back to regular characters. I am particularly uncertain about the behavior of thi ...

What is the best way to define a custom route in react-router-dom?

My goal is to have the URL display "/login" in the address bar when I am on the login page. // App.js <Routes> {isLoggedIn ? ( <Route path="/" element={<Root onLogout={handleLogout} />}> <Route index e ...

ajax not correctly handling errors when SQL connection fails

When using ajax to make a request to a PHP page that connects to a MySQL database, I encountered an issue. Even if the MySQL service is turned off, the success part of the ajax call still triggers. $.ajax({ type: "POST", url: "ajax.php", time ...

Handling 404 Response from WebAPI in $Http.get() Function

While using my web application, I am executing a GET command to access a remote HTTP WebAPI service. $http.get(url).then(function(data) { do_something(); }); When the WebAPI successfully returns data, everything functions as expected. However, in cases w ...

"Enhancing ASP.NET localization through the implementation of Page Methods and Web Services using AJAX

It's quite complicated... We are facing an issue with client-side validation through AJAX calls to page methods, acting as web services. Additionally, we have implemented a drop-down menu for language selection and a class that extends Page to handle ...

Guide on enabling the Access-Control-Allow-Origin feature for Angular 5 and Node.js:

After exploring various methods to include 'Access-Control-Allow-Origin', I have not been successful in resolving the issue. I am utilizing the @angular/common/http module with an external URL as a data source. However, when attempting to retrie ...

Is it possible to create a Facebook reveal tab using either Javascript or .NET?

As a developer who jumped into Facebook development just before the recent changes, I am feeling lost when it comes to building apps now. I see many questions similar to mine about creating fan-gating features using Javascript only. Is there an up-to-date ...

Managing window popups using WDIO - tips and tricks

Having some trouble handling a facebook auth dialog popup through webdriverio. Struggling to target the email and password fields for the facebook signup process. Below is the code in question: it('redirects after signup', () => { browse ...

When attempting to retrieve JSON data for the second time, AJAX fails to fetch the information

After successfully sending an Ajax request to a php file and receiving a JSON array of the submitted data, I encountered an error on the second attempt. The error message reads: SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSO ...

Discovering a way to capture the space bar event in a number input field with JavaScript

Is there a way to capture space bar input with an onchange event in JavaScript? <html> <head> <script type = "text/javascript"> function lala(aa){ console.log(aa + " dasda"); } </script> </head> <body> <input ty ...

Using the i18next Module for Localization in ExpressJS and Front-End Development

I am currently integrating the i18next module into my NodeJs/ExpressJS web application. All the translation files are stored in the /locales directory. According to information from i18next.com, it can also be utilized on the client side. <script typ ...

Exploring the functionality of Kendo Grid within an Angular application

Currently, I am facing some challenges while trying to execute my Karma tests using the kendo grid within a fresh Angular project. The specifications for this specific component are outlined below: import { async, ComponentFixture, TestBed } from '@a ...

Facing issue with Codeigniter AJAX form where post data is not being collected

I am attempting to send a newsletter form to Codeigniter using AJAX. I have implemented CSRF protection, but I am facing issues with retrieving the posted values and receiving the response correctly. Here are the various scenarios: When I include name="e ...