Julian
Julian

Reputation: 27

Loading json into chart.js

I want to load jsonData via ajax into a chart.js object.

My problem is by refering the jsondata as string to chart.js

I think the ajax().responseText retrieves a string but chart.js data expects an array?

I'm doing the same with google chart and it works very well.

Here is my code:

<html>
    <head>
    <script type="text/javascript" src="./jquery-3.1.1.min.js"></script>
    <script type="text/javascript" src="./jslib.js"></script>
    <script type="text/javascript" src="./Chart.min.js"></script>
    </head>

    <body>
        <div class="container">
          <h2>Chart Test</h2>
          <div>
            <canvas id="myChart"></canvas>
          </div>
        </div>
         <script type="text/javascript">
            var jsonData = $.ajax({
                type: "POST",
                data: { "ibrconfig_id": 26}, 
                url: "./ibrlib.php",
                dataType:"json",
                async: false
                }).responseText;   
            //document.write(jsonData);//   this returns: { labels: ["1","2"], datasets: [ { label: "Taster", data: [0,0], backgroundColor: "rgba(153,255,51,0.6)" } ] }    
            var ctx = document.getElementById('myChart').getContext('2d');
            var myChart = new Chart(ctx, 
            {
                type: 'bar',
                data: jsonData
            });

            /*
            This works very fine
            var ctx = document.getElementById('myChart').getContext('2d');
            var myChart = new Chart(ctx, 
            {
                type: 'bar',
                data: { labels: ["1","2"], datasets: [ { label: "Taster", data: [0,0], backgroundColor: "rgba(153,255,51,0.6)" } ] }
            }); 
            */      
        </script>
    </body>
</html>   

How can I handle this? Thank you very much for your time!

Upvotes: 3

Views: 680

Answers (2)

Julian
Julian

Reputation: 27

Ok I got it. thank you andr1o

my jsonData was wrong.

{ labels: ["1","2"], datasets: [ { label: "Taster", data: [0,0], backgroundColor: "rgba(153,255,51,0.6)" } ] }

no i changed it to

 { "labels": ["1","2"], "datasets": [ { "label": "Taster", "data": [0,0], "backgroundColor": "rgba(153,255,51,0.6)" } ] }

Upvotes: 1

andr1o
andr1o

Reputation: 259

Use JSON.parse(jsonData) to make an Object from json string

Upvotes: 0

Related Questions