Cat Overlord
Cat Overlord

Reputation: 173

Put JSON data into chart.js pie chart

I have this JSON data I would like to put into a Chart.js chart:

[
{
"data": "1st",
"count": "166"
},
{
"data": "2nd",
"count": "24"
},

{
"data": "3rd",
"count": "65"
}
]

Chart.js:

    var pieData = [

            {
                value: 300,
                color:"#F7464A",
                highlight: "#FF5A5E",
                label: "Red"

            },
            {
                value: 40,
                color: "#949FB1",
                highlight: "#A8B3C5",
                label: "Grey"
            },

            {
                value: 166,
                color: "#4D5360",
                highlight: "#616774",
                label: "Blue"
            }
        ];

        window.onload = function(){
            var ctx = document.getElementById("chart-area").getContext("2d");

            window.myPie = new Chart(ctx).Pie(pieData);
        };

Javascript loading JSON:

var xmlhttp = new XMLHttpRequest();
var url = "chart.json";

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var myArr = JSON.parse(xmlhttp.responseText);
        myFunction(myArr);
    }
}
xmlhttp.open("GET", url, true);
xmlhttp.send();

function myFunction(arr) {
    var out = "";
    var i;
    for(i = 0; i < arr.length; i++) {

        out +=  arr[i].data + arr[i].count;


    }
    document.getElementById("nooo").innerHTML = out;
}

But this only puts the data into a single element. Is there any way you can put the data into variables for the pie graph's value and label values ? (if I wasn't clear enough, see my example) -

var pieData = [

        {
            value: count,
            color:"#F7464A",
            highlight: "#FF5A5E",
            label: data

        },
        {
            value: count,
            color: "#949FB1",
            highlight: "#A8B3C5",
            label: data
        },

        {
            value: count,
            color: "#4D5360",
            highlight: "#616774",
            label: data
        }
    ];

How would you do this ?

Upvotes: 0

Views: 4639

Answers (1)

Kyle
Kyle

Reputation: 66

$.ajax({
       url: 'chartpi.php',
       success: function (response) {//response is value returned from php
            alert(response); //showing response is working
            var datachart = JSON.parse(response);
            var ctx2 = document.getElementById("chart-area2").getContext("2d");
            window.myPie = new Chart(ctx2).Pie(datachart);
       }
    });

Upvotes: 2

Related Questions