A Pie chart using AJAX and JSON
As well as the RGraph.AJAX.getNumber
, RGraph.AJAX.getString
and
RGraph.AJAX.getCSV
canvas
ajax
functions there's also a convenient way to fetch
json
content from your server by way of the RGraph.AJAX.getJSON
function.
Since the responses to ajax
calls start as strings this function handily converts the response
into a javascript
object automatically for you.
As you can see from the example below this means that you can use the response directly in any
chart configuration (ie the json.data
and json.labels
variables).
This demo page is intended to show the ajax
and json
functionality that RGraph has so the rest of
the Pie chart
configuration is pretty straightforward.
The Pie chart
does have a key though - which together with the tooltips use the labels which
are part of the json
response.
Added in March 2020 was the new feature of tooltip templates and the use of the
tooltipsCss
property - which makes it much easier to add custom styles to your tooltips.
This goes in the documents header:
<script src="RGraph.common.core.js"></script> <script src="RGraph.common.dynamic.js"></script> <script src="RGraph.common.tooltips.js"></script> <script src="RGraph.common.key.js"></script> <script src="RGraph.pie.js"></script>Put this where you want the chart to show up:
<div style="float: right"> <canvas id="cvs" width="450" height="350">[No canvas support]</canvas> </div>This is the code that generates the chart - it should be placed AFTER the
canvas
tag(s):
<script> // Use the AJAX function RGraph.AJAX.getJSON to fetch some JSON from the server. // When you make an AJAX request to the server the reponse is a string - so RGraph // will convert the response to JSON for you automatically. The function is given // the URL of the AJAX script and a callback function that creates the chart. Here // the data (json.data) and the labels (json.labels) are used in the configuration. RGraph.AJAX.getJSON('/getdata.html?json', function (json) { var pie = new RGraph.Pie({ id: 'cvs', data: json.data, options: { tooltips: 'Score for <b>%{property:myNames[%{index}]}</b> was %{value_formatted}', tooltipsFormattedUnitsPost: '%', tooltipsCss: { fontSize: '18pt' }, myNames: json.labels, shadow: false, key: json.labels, keyPositionGraphBoxed: false, colors: ['red','gray','#afa','blue','pink','yellow','black','orange','cyan','purple'], centerx: 175, responsive: [ {maxWidth:null,parentCss:{'float':'right',textAlign:'none'}}, {maxWidth:750,parentCss:{'float':'none',textAlign:'center'}} ] } }).draw(); }); </script>