Utilize XML and Javascript to create a captivating donut chart

I am currently experimenting with XML and JavaScript to generate a donut chart.

I attempted to implement this JS code. However, I am struggling to create XML that is compatible with the JS.

var SCIENCE = 0;
var ART = 0;
var MATH = 0;

$(document).ready(function() {
  $.ajax({
    type: "GET",
    url: "abc.xml",
    dataType: "xml",
    success: function(xml) {

      var prog = $(this).text();

      $(xml).find('course').each(function() {
        var prog = $(this).text();

        if (prog == "SCIENCE") {
          SCIENCE++;
        } else if (prog == "ART") {
          ART++;
        } else if (prog == "MATH") {
          MATH++;
        }

      });
      visualizeIt();
    },
    error: function() {
      alert("An error occurred while processing XML file.");
    }
  });
});

function visualizeIt() {
  var total = SCIENCE + ART + MATH;
  var pSCIENCE = (SCIENCE / total) * 100;
  var pART = (ART / total) * 100;
  var pMATH = (MATH / total) * 100;

  var width = 960,
    height = 500,
    radius = Math.min(width, height) / 2;

  var vis = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
    .append("g")
    .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

  var cScale = d3.scale.linear().domain([0, 100]).range([0, 2 * Math.PI])
  data = [
    [0, pSCIENCE, "#3399FF", "SCIENCE"],
    [pSCIENCE, pSCIENCE + pART, "#FF9966", "ART"],
    [pSCIENCE + pART, 100, "#FF99FF", "MATH"]
  ]

  var arc = d3.svg.arc()
    .innerRadius(150)
    .outerRadius(220)
    .startAngle(function(d) {
      return cScale(d[0]);
    })
    .endAngle(function(d) {
      return cScale(d[1]);
    });

  var g = vis.selectAll(".arc")
    .data(data)
    .enter().append("g")
    .attr("class", "arc");

  g.append("path")
    .attr("d", arc)
    .style("fill", function(d) {
      return d[2];
    });

  g.append("text")
    .attr("transform", function(d) {
      return "translate(" + arc.centroid(d) + " ) ";
    })
    .attr("dy", ".35em")
    .style("text-anchor", "middle")
    .text(function(d) {
      return d[3];
    });
}

I am new to working with XML. I am uncertain about how to structure the XML code to interact with the JS.

Any guidance on this matter would be greatly appreciated.

Answer №1

A simple XML example is shown below:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<data>
    <item>APPLE</item>
    <item>BANANA</item>
    <item>ORANGE</item>
    <item>STRAWBERRY</item>
    <item>APPLE</item>
    <item>BANANA</item>
    <item>ORANGE</item>
    <item>STRAWBERRY</item>
    <item>BANANA</item>
    <item>ORANGE</item>
</data>

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

Encountering numerous TypeScript errors due to a JavaScript file in Visual Studio 2017

Kindly review the update below I utilized the following package as a foundation for my VS Project -> https://github.com/AngularClass/angular2-webpack-starter Everything ran smoothly in Visual Studio Code, but when I attempted to convert it into a Visu ...

I implemented a proxy in my project to handle cross-domain requests, however, the requested address changes when I make a

Unable to Cross Domains http://localhost:8080/api/login has to be redirected to http://localhost:8080/index.html proxyTable: { '/api': { target: 'http://47.106.74.67:8080', changeOrigin: true, pathRewrite: ...

Error in AJAX POST: base64 string formatting issue

Struggling with making an AJAX POST successfully upload and retrieve a base64 string to/from my SQL database. Upon receiving the string from the database via AJAX, it appears to be the same base64 string, but with random line breaks that render it non-func ...

"Switching a div's visibility when a link is clicked

http://jsfiddle.net/FsCHJ/2/ Currently, when I add another link, it automatically uses the same functionality as the toggle button. What I want is for "Toggle Edit Mode" to toggle a hidden div on and off. I attempted to modify the code from $("a").click(f ...

Tips for preventing multiple links from opening when clicking the same link

Having a data grid with a hyperlink control that allows users to open a new tab displaying selected item information poses the issue of multiple tabs opening when the same item is clicked multiple times. Is there a way to have the tab open only the first t ...

Error encountered in Angular JS: $parse:syntax Syntax Error detected

var app=angular.module('myapp',[]) app.controller('myctrl',Myfunction); function Myfunction($scope,$compile){ var self=this; $scope.text=s4(); $scope.adding=function(){ var divElement = angular.element($("#exampleId")); ...

Leveraging anonymous functions within an IF statement in JavaScript

Can you explain how to implement an anonymous function within an if statement? Feel free to use the provided example. Thank you if(function(){return false;} || false) {alert('true');} For more information, visit https://jsfiddle.net/san22xhp/ ...

Having trouble with the :first-of-type Pseudo Class in CSS?

I have been attempting to style the first link in an li element with a specific font color. When the li element is clicked, it gains the "open" class. I've tried using both li a:first-of-type and li a:first-child pseudo-classes to achieve this, but ...

Transferring Information to a Web Application

Hey there! So, I have a Web App that relies on JSON data. I've been pondering the idea of loading this data as a variable from an external script using a standard HTML tag versus utilizing the jQuery AJAX method for data loading. If I go with the ext ...

Automatically inserting a row into an HTML table

My table structure looks like this: <form name="frm_data_nasabah2" method="post" enctype="application/x-www-form-urlencoded" action="<?php echo $page_action;?>"> <table class="table table-bordered table-hover" id="tab_logic_ ...

What is the best way to group data by a specific value within a nested object when using ReactJS material-table?

I have a unique scenario where I possess an array of individuals featuring a nested object known as enterprise. My objective is to effectively group these individuals by the value of company.name within the confines of the Material-Table. const people = [ ...

Targeting multiple browsers in an Angular 11 project with scss: A comprehensive guide

for instance: i'm currently animating the ::placeholder pseudo element when ::focus is active input::placeholder{ color: grey; transition: all 400ms ease; position: absolute; top: 35%; font-size: 15px; } inpu ...

Tips for generating automatic views in Backbone without manual instantiation

Is there a more efficient way to instantiate the view rather than directly below the definition? var BVApp = Backbone.View.extend({ Name: 'BVApp', // do chonka stuff }); $A.Class.add(new BVApp()); ...

Stripping CSS prefixes upon file initialization

When developing my application, I have a process in place where I load CSS files on the back-end using Express.JS and then transmit them to the front-end. However, before sending the CSS code to the front-end, I need to: Identify the user's browser; ...

Trouble with Vuex Store: Changes to table values not reflected in store

I've been tackling a table project using Quasar framework's Q-Popup-edit and Vuex Store. The data populates correctly initially. However, any changes made on the table do not seem to persist and revert back to their original values. Here is a s ...

Issue: A SyntaxError is triggered due to an unexpected termination of the JSON input while utilizing the fetch()

I encountered an issue while working on sending JSON between a Go API server and a React front-end. The error message I received was: Error: SyntaxError: Unexpected end of JSON input The specific line where the error is occurring is Line 25, which contai ...

Is there a way to detect when the browser's back button is clicked?

As I work on supporting an e-commerce app that deals with creating and submitting orders, a user recently discovered a loophole wherein they could trigger an error condition by quickly pressing the back button after submitting their order. To address this ...

Navigate through information within designated boundaries

In order to achieve vertical scrolling of a sidebar div and its content (3 links) between two points, I have utilized the CSS property position:fixed; top: 100px. While this setup works well initially by positioning the sidebar 100px down from the top and ...

How to eliminate properties from a nested array using D3

I've been attempting to filter out specific attributes from an array using D3. The array consists of values from a CSV file. Everything went smoothly for a small CSV file when I did it like this: d3.csv("foods.csv", function(data) { data.forEach(fun ...

Need to invoke a controller method multiple times? Utilize AJAX for seamless and efficient execution

Apologies if this question seems simple, but I'm struggling to find a solution. I've implemented a straightforward method in a controller: public string ExactSeconds() { string str = DateTime.Now.Second.ToString(); return str; ...