Share RGraph:
Share RGraph on Twitter Share RGraph on Google Plus Share RGraph on Facebook Follow RGraph on LinkedIn

How to use JSON encoded data

[No canvas support]

A popular way to transfer data in Javascript, particularly if you're using AJAX, is JSON. This greatly simplifies the transfer of data structures when you're passing information from a server to the client. Using JSON with RGraph is easy and can be an easy way to get your data into a form usable by RGraph.


<script>
        // If this is retrieved via an AJAX request it will be a string and you will need to use the eval() function to
        // change it into a Javascript object.

        var myJSONData = {
                          'data': [9,8,3,6],
                          'labels': ['Bob','Lucy','Gary','Hoolio'],
                          'tooltips': ['Bob did well','Lucy had her best result','Gary - not so good','Hoolio had a good start']
                         }
        
        var myChart = new RGraph.Bar('cvs', myJSONData.data)
            .set('tooltips', myJSONData.tooltips)
            .set('labels', myJSONData.labels)
            .draw();
     
</script>

If you use key names that match the RGraph property names then you can ease the process of setting the configuration of your object by using the RGraph.SetConfig() function. For example:

<script>
        var myJSONData = {
                          'labels': ['Bob','Lucy','Gary','Hoolio'],
                          'tooltips': [
                                       'Bob did well',
                                       'Lucy had her best result',
                                       'Gary - not so good',
                                       'Hoolio had a good start'
                                      ]
                         }
        
        var myChart = new RGraph.Bar('cvs', [9,6,2,5]);
        RGraph.SetConfig(myChart, myJSONData);
        myChart.draw();
     
</script>

Note about JSON data and AJAX

If you're retrieving your data via AJAX it's returned as a string. So the thing to do here is use the eval() function to convert it to an actual Javascript structure. If you're doing this you need to wrap the whole string in parentheses to have the data structure entirely preserved - like this:
<script>
    window.onload = function ()
    {
        RGraph.AJAX(url, myFunc);
    }
    
    function myFunc ()
    {
        // The responseText is the output of the AJAX request - our JSON data that needs to be eval()'ed
        var data = eval('(' + this.responseText + ')');
        
        // ...
    }
</script>

© Copyright 2014 Richard Heyes All rights reserved.