1

I am trying to populate a piechart in ChartJS dynamically using data from a jQuery/AJAX query.

The only thing I am struggling with is creating the data in a format that chartJS understands. This is the required format:

var dynamicData = [
    { label: "One", value: 23 },
    { label: "Two", value: 33 },
    { label: "Three", value: 43 },
    { label: "Four", value: 53 },
]

When I try to create it, I get double quotes "" around each set of data. I know it is a simple mistake but I can't figure it out. This is how I am creating the data (partial jQuery code):

.success(function(response) {
    if(!response.errors && response.result) {
        var doughnutData = [];
        $.each(response.result, function( index, value) {
            doughnutData.push('{ label: "'+value[0]+'", value: '+value[2]+',color:"#F7464A" }');
       });

        console.log(doughnutData);

var doughnutOptions = {
    segmentShowStroke : true,
    segmentStrokeColor : "#fff",
    segmentStrokeWidth : 2,
    percentageInnerCutout : 50,
    animation : true,
    animationSteps : 100,
    animationEasing : "easeOutBounce",
    animateRotate : true,
    animateScale : true,
    onAnimationComplete : null
}
var ctx = document.getElementById("chart3").getContext("2d");
var mydoughnutChart = new Chart(ctx).Doughnut(dynamicData, doughnutOptions);
    } else {
    alert("error");
    }

The console shows:

["{ label: "17x1p14e6662", value: 16,color:"#F7464A" }", "{ label: "8734hjgfd784ew", value: 8,color:"#F7464A" }"]

What am I doing wrong?

1 Answer 1

1

The console is outputting the object as a string because you are pushing a string to the var doughnutData, you are doing this wrapping the object in quotes and concatenating the values to the string therefor treating the argument passed to the push method as a string type.

The proper way to use the push method to add an object to an array would be like this.

array.push({property:'string', property:2})

Meaning your code should look like this.

doughnutData.push({ label:value[0], value:value[2],color:"#F7464A" });

Here is a link on how the push method works on an array and Here is another link to javascript objects

Another thing is when you are creating the chart your are passing the var dynamicData instead of your var doughnutData.

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome! I understand the issue now. Thanks for taking the time to answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.