Feed XML data into Google Charts



I need to feed a google chart with xml data. I managed to read the xml file using jquery but I'm struggling to feed this data into the javascript drawChart function used in the google charts. The below is the code I have written so far. Can someone tell me the code to feed this data to the drawChart function.


Thanks


The HTML and Javascript



<!DOCTYPE html>
<html>
<head>

<script type="text/javascript" src="http://ift.tt/1GUSn0v"></script>

<script type="text/javascript" src="http://ift.tt/JuZcy0"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);

$(document).ready(function() {
$.ajax({
type: "GET",
url: "ChartData.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('Pie').each(function() {
var sTitle = $(this).find('Title').text();
var sValue = $(this).find('Value').text();

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

function drawChart() {

var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);

var options = {
title: 'My Daily Activities'
};

var chart = new google.visualization.PieChart(document.getElementById('piechart'));

chart.draw(data, options);
}
</script>

<title>My Read</title>
</head>

<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>


The XML FIle



<?xml version="1.0" encoding="utf-8" ?>
<Chart>
<Pie>
<Title>Work</Title>
<Value>11</Value>
</Pie>
<Pie>
<Title>Eat</Title>
<Value>2</Value>
</Pie>
<Pie>
<Title>Commute</Title>
<Value>2</Value>
</Pie>
<Pie>
<Title>Watch TV</Title>
<Value>2</Value>
</Pie>
<Pie>
<Title>Sleep</Title>
<Value>7</Value>
</Pie>
</Chart>

No comments:

Post a Comment