Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse XML data into Chart.js Line Chart

I'm trying to combine two javascripts into one but am struggling to get it to work. I'm not sure if what I'm trying to do is possible, but I thought stackoverflow is the best place to get help.

The first javascript is Chart.js, specifically the Line Chart option. The second script is an XML in HTML script by w3schools.

What I would like to do is using an XML file to populate the data for the line chart. I modified the code accordingly, but I have only very basic knowledge of javascript and couldn't get it to work. This is what I tried:

<canvas id="canvas1" width="350" height="300"></canvas>
<script>
   if (window.XMLHttpRequest)
   {    // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
   }
   else
   {    // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
   xmlhttp.open("GET","data_chart.xml",false);
   xmlhttp.send();
   xmlDoc=xmlhttp.responseXML; 

   var x=xmlDoc.getElementsByTagName("Row")
   for (i=0;i<x.length;i++)

   var lineChartData = {
                labels : ["1","2","3","4","5"],
                datasets : [{
                     fillColor : "rgba(0,0,0,0.5)",
                     strokeColor : "rgba(0,0,0,1)",
                     pointColor : "rgba(0,0,0,1)",
                     pointStrokeColor : "#fff",
                     data : [x[i].getElementsByTagName("data_chart_1")]
                   }]
           }
   var myLine = new   
   Chart(document.getElementById("canvas1").getContext("2d")).Line(lineChartData);

</script>

So, the idea is that the data section of the variable lineChartData is populated by getting all elements in the row data_chart_1 from the XML file data_chart.xml. Is something like this possible? How would I have to update the code to make this work?

Thank you very much for your help. I hope my question was clear.

like image 440
rf2012 Avatar asked Mar 03 '26 05:03

rf2012


1 Answers

Try this

var firstRow = xmlDoc.getElementsByTagName("Row")[0];
//console.log(firstRow);
var dataChart = firstRow.firstChild.nodeValue;
//console.log(dataChart);
var chartData = dataChart.split(",");
.......................
data : chartData
like image 90
naveen Avatar answered Mar 04 '26 20:03

naveen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!