0

I have an issue which hope can get help with. I've read a few tutorials and also a few questions on here but none seem to answer my question. I'm making an ajax request to my PHP file which is coming back with a JSON response something like this for example (console logged output):

{ Email addresses: 4, IP addresses: 2, Names: 1 }

I would like to be able to take this and plot it onto a chart using Chart.js however I have tried:

$.each(res, function(i, item) {
    data = {
        label: i,
        value: item
    }
}
var myDoughnutChart = new Chart(ctx).Pie(data);

Problem is it's only filling with one color and one label with one value. Is there any way I can change the the format of the JSON output so it might read:

{ "Label":"Email addresses","Value":"4" }

The change would have to be made using Javascript/JQuery. I must point out the labels aren't always the same as sometimes the JSON output might be different like:

{ Usernames: 3, Passwords: 3, Names: 1 }

Again the above is only what I'm getting when outputting to the console.

How would I also go about charting this maybe using a $.each() in JQuery or other? Any help would be appreciated, sorry for the length of this question.

1
  • You overwrite data with each iteration of the loop. Try data.push({label: i, value: item}); instead. And make sure data is an array first. Commented Mar 30, 2016 at 1:48

2 Answers 2

2

You always override data when you make it equal with the current item and will be equal to the last element after the cycle. You need to add elements to it, so there will be more elements in the chart.

$.each(res, function(i, item) {
    if (!Array.isArray(data)) {
        data = [];
    }
    data.push({
        label: i,
        value: item
    });
}
var myDoughnutChart = new Chart(ctx).Pie(data);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks guys, that worked well for me. I appreciate the help.
0

its very easy

go to chart.js script and replace label and value with Email addresses and ip addresses.. initially it was accepting label and value and some optional properties like color and all...

hope it vl help

Comments

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.