Having trouble loading a chart with amcharts after sending an ajax request

I have integrated amcharts to create a pie chart. When I click a button, an AJAX request is triggered to fetch data from MySQL in JSON format.

After receiving the JSON array, I pass the data to amcharts but the chart doesn't display. Oddly, if I redirect to a new JSP page, the chart appears as expected.

Here is my HTML code:

<input type="submit" class="btn btn-success" name="shift" value="shift analysis" onclick="shift(a,b,c,d)">
<div id="chartdiv1" style="width: 640px; height: 400px;"></div>

var chart = AmCharts.makeChart("chartdiv1", {
      "type": "pie",
      "theme": "light",
     
      "valueField": "f2",
      "titleField": "t",
       "balloon":{
       "fixedPosition":true
      },
      "export": {
        "enabled": true
      }
    } );
       
    
    
    
    function shift(a,b,c,d)
     {
      var ajax_req =new XMLHttpRequest();
      var method = "GET";
      var url ="endpoint";
      var asynchronous = true;
      
      ajax_req.open(method, url, asynchronous);
      ajax_req.send();
      
      ajax_req.onreadystatechange = function()
            {
        if (this.readyState == 4 && this.status == 200) 
               {
         // document.getElementById("json").innerHTML = this.responseText;
         
        var result= this.responseText;
         alert(result);
                chart.dataProvider =result;
        chart.validateNow();
    
               }
        }
      }

For clarity, here is the output of my AJAX request: result: [{"t":"01:11","f2":340},{"t":"01:11","f2":335},{"t":"01:09","f2":334}]

Answer №1

Even if the response you receive in your XMLHttpRequest callback is in JSON format, the responseText will still be a string type (you can verify this by checking typeof this.responseText in your debugger). You must manually convert this response to a JavaScript array before assigning it to the dataProvider. To do this, use JSON.parse:

chart.dataProvider = JSON.parse(result);

Additionally, ensure that you call validateData to update the chart. The method validateNow skips data validation by default when omitting the first parameter and is usually used for updating visual properties.

Check out a demo using jsfiddle echo

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

How come I'm unable to send the HTTP request contents as a response using express.js?

I'm currently in the process of setting up a basic web server using node.js and express.js. Essentially, I want the server to return the content of the request as a response. Below is the code I have implemented: const express = require('express& ...

Ways to incorporate ng-app into an HTML element when HTML access is limited

In my current project, I am using Angular.js within a template system. The challenge I am facing is that I need to add ng-app to the html element, but I do not have direct access to do this on the page itself. Initially, my page structure looks like this: ...

Is it a guarantee that a function called in the head section of a JavaScript for-of loop will only be executed once?

In both Firefox and Chrome, I tested the code snippet below: function test() { console.log("***") return [1,2,3] } for (const t of test()) { console.log(t) } After running this code, I noticed that the test function was only called once. T ...

Using AJAX requests and $watch in AngularJS purposes

When a button is clicked, I want to dynamically generate a select menu. Using an ajax call, I retrieve JSON data from an external file upon the button click event. However, the select menu only updates with the JSON data after clicking the button twice. I ...

A Step-by-Step Guide to Setting Up and Utilizing V-Calendar in Vue.js

I am currently trying to incorporate the V-Calendar library into my Vuetify application. Up until now, the app was working fine, but I seem to have hit a roadblock with the correct installation of the V-Calendar library. Although no error messages are bei ...

Iterate over a JSON object to calculate the total sum of values based on distinct nested properties

Here is a JSON object that contains cost and author information. I am working on this in Express.js and using Underscore. [ { "Cost": 250, "author": { "id": "2", "name": "Joe", "workId": "5" } }, { ...

Create a chronological timeline based on data from a JSON object

Here is a JSON object generated by the backend: { "step1": { "approved": true, "approvalTime": "10-11-2021", "title": "title 1", "description": "description 1" ...

400 Error: Frustrating AJAX POST Request Woes

Attempting to send data to a controller using the POST method with jQuery AJAX. Below is the code being used: $('#save_new').on('click', function () { var category_name = $('#new_category').val(); ...

Struggling to properly interpret the unrefined data from Typeform's webhook

Utilizing the webhook feature of Typeform to convert results to JSON when a user submits the embedded survey is working perfectly when tested with RequestBin. However, after exposing my local app using ngrok with the command ngrok http 3000 and setting t ...

Ways to resolve a 500 internal error

I have created an online test system for students, but I am facing an issue with passing answers in JSON format. Whenever I attempt to do so, I encounter a 500 internal error and I am unable to identify the root cause. Even after removing lengthy JSON dat ...

Retrieve the present value from a Selectpicker using jQuery within the Codeigniter Framework

I attempted to use DOM manipulation to retrieve the value of the currently selected option from the selectpicker. My goal was to have the value of the selectpicker id="service_provider_select" printed first. However, whenever I changed the option using the ...

Broadcast signals to an overarching frame

I have successfully embedded a chatbot (Angular 14 app) in an iframe and now I need to determine whether the frame should be minimized so it can fit within the parent container. My goal is to send custom events to the receiving frame. let iframeCanvas = do ...

Employing the findOne method repeatedly in a loop can significantly slow down operations in Node.js

Currently, I am working on a project using Node.js in conjunction with MongoDB, specifically utilizing Monk for database access. The code snippet I have is as follows: console.time("start"); collection.findOne({name: "jason"}, function(err, document) { ...

Divide the Javascript code from the HTML Canvas

I have been diving into HTML5 Canvas and exploring how to implement it using Javascript code. However, I am facing difficulties separating the Javascript code from the original html file. Despite trying some solutions: HTML5 Canvas not working in extern ...

Steps to modify the button color within a sub-menu by leveraging vue js3 and element-plus

After creating a button in a sub-menu that should change color when clicked, I am struggling to make it work. Below is the code for the button: In addition to this code snippet, I have added more code which can be found here I also want to change the co ...

Having trouble with the JavaScript DOM rewrite for aligning text?

function modifyTextAlignment(){ document.getElementById("th1").style.textAlign = "right"; } #th1{ text-align:left; } <table> <tr><center><th colspan="2" id="th1">List of Important Emergency Contacts</th><center></tr& ...

Transforming numbers into arrays in JavaScript/TypeScript for Angular 7

What is the best way to convert the number 10 into an array in JavaScript? expected output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] OR How can I transform the number 10 into the number of items within an array using JavaScript? ...

Issue encountered during Node.js installation

Every time I attempt to install node js, I encounter the following errors: C:\Users\Administrator>cd C:/xampp/htdocs/chat C:\xampp\htdocs\chat>npm install npm WARN package.json <a href="/cdn-cgi/l/email-protection" class ...

The largest contentful paint is anticipating an unidentified event

My website is encountering issues with Google Pagespeed and I'm unsure of the cause. The primary bottleneck appears to be the LCP time, which Google reports as taking between 7 and 11 seconds during each test. Upon analyzing the waterfall chart, it ...

Encountered a connection error while attempting to establish a connection in Node.js

Every time I try to execute the code, I encounter this error message: throw new Error('Most middleware (like ' + name + ') is no longer bundled with express and must be installed separately ^ Error: Most middleware(like BodyParser) is ...