0

I've been trying to get doughnut chart to work with my CI3 application to no avail as this is my first time trying ChartJS out.

What I tried

-PHP

public function get( $data ) {
    if ( $this->input->is_ajax_request() ) {
        $this->load->library('user_utils');

        if ( $data == 'subscriptions' ) {
            $this->load->model('Fetcher', 'fetcher');

            $options = [
               // Database specific key/value pairs
            ];

            $fetch = $this->fetcher->fetch( 'where', $options );

            if ( $fetch ) {
                echo json_encode( $fetch->result_array() ); 

                // needs review
                $fetch->free_result();
            } else {
                print json_encode( 'false' );
            } 
        }
    } else {
        show_404();
    }
}

-JS

$(function() {
if ($("#subChart").length) {
    // donut chart data
    jQuery.ajax({
        type: "GET",
        url: 'dashboard/get/subscriptions',
        success: function(response) {
            console.log(response);

            var subscriptions = {
                status : []
            };
            var len = response.length;

            for (var i = 0; i < len; i++) {
                subscriptions.status.push(response[i].subscriptions);
            }
            var chart = $("#subChart");
            var fontFamily = '"Proxima Nova W01", -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif';

            // set defaults
            Chart.defaults.global.defaultFontFamily = fontFamily;
            Chart.defaults.global.tooltips.titleFontSize = 14;
            Chart.defaults.global.tooltips.titleMarginBottom = 4;
            Chart.defaults.global.tooltips.displayColors = false;
            Chart.defaults.global.tooltips.bodyFontSize = 12;
            Chart.defaults.global.tooltips.xPadding = 10;
            Chart.defaults.global.tooltips.yPadding = 8;
            var data = {
                labels: ["Processed", "Pending", "Cancelled"],
                datasets: [
                    {
                        data: subscriptions.status,
                        backgroundColor: ["#85c751", "#6896f9", "#d97b70"],
                        hoverBackgroundColor: ["#85c751", "#6896f9", "#d97b70"],
                        borderWidth: 0
                    }
                ]
            };

            // -----------------
            // init donut chart
            // -----------------
            new Chart(chart, {
                type: 'doughnut',
                data: data,
                options: {
                    legend: {
                        display: false
                    },
                    animation: {
                        animateScale: true
                    },
                    cutoutPercentage: 80
                }
            });
        }
    })
}
});

I'm getting the chart data through ajax on page load, what i'm i missing?, should I set default chart data and update them after fetching thorugh ajax first? Your answer will be highly appreciated, thanks.

5
  • 1
    The answer to your last question is yes, you should set some default chart data, probably to 0 or 360 degrees, or however chartjs does donuts. When you get the response back, is it what you are expecting? Commented Dec 16, 2017 at 2:54
  • console log is your friend Commented Dec 16, 2017 at 5:01
  • @Alex that has not been helpful :-( Commented Dec 16, 2017 at 6:13
  • @BrianGottier sorry for the late response. Forgive me for not going through the ChartJS documentation properly, i was in a hurry to get it working. Didn't know there's an update method. But i was expecting some sort of data update to MAGICALLY happen too. Will try setting default values and calling the update() method. Commented Dec 16, 2017 at 6:17
  • @BrianGottier did what you suggested after going through the documentation and it worked impressively fine, thanks man. Will post the working solution as an answer now Commented Dec 16, 2017 at 11:25

1 Answer 1

0

After going through the ChartJS documentation, I found and utilized the .update(config) method after previously initializing my chart with dummy data. Here's what the JavaScript file looks like now:

$(function() {
if ($("#subChart").length) {
    var chart = $("#subChart");
    var fontFamily = '"Proxima Nova W01", -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif';
    
    // set defaults
    Chart.defaults.global.defaultFontFamily = fontFamily;
    Chart.defaults.global.tooltips.titleFontSize = 14;
    Chart.defaults.global.tooltips.titleMarginBottom = 4;
    Chart.defaults.global.tooltips.displayColors = false;
    Chart.defaults.global.tooltips.bodyFontSize = 12;
    Chart.defaults.global.tooltips.xPadding = 10;
    Chart.defaults.global.tooltips.yPadding = 8;
    var data = {
        labels: ["Processed", "Pending", "Cancelled"],
        datasets: [
            {
                data: [1, 1, 1],
                backgroundColor: ["#85c751", "#6896f9", "#d97b70"],
                hoverBackgroundColor: ["#85c751", "#6896f9", "#d97b70"],
                borderWidth: 0
            }
        ]
    };

    // -----------------
    // init donut chart
    // -----------------
    var subsChart = new Chart(chart, {
        type: 'doughnut',
        data: data,
        options: {
            legend: {
                display: false
            },
            animation: {
                animateScale: true
            },
            cutoutPercentage: 80
        }
    });

    // donut chart data
    jQuery.ajax({
        type: "GET",
        url: 'dashboard/get/subscriptions',
        success: function(response) {
            console.log(response);

            var obj = JSON.parse(response);
            console.log(obj);
            console.log(obj[0].count);

            var active = obj[0].count;
            var pending = obj[1].count;
            var cancelled = obj[2].count;

            console.log('Initial value:' + subsChart.data.datasets[0].data);
            subsChart.data.datasets[0].data[0] = active;
            subsChart.data.datasets[0].data[1] = pending;
            subsChart.data.datasets[0].data[2] = cancelled;
            subsChart.update(); 

            console.log('Updated value:' + subsChart.data.datasets[0].data);
        }
    })
 }
});

and here's the output: Browser Output

Many thanks to @briangottier

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

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.