Chartjs-Pie chart using chart.js and asp.net web Service (asmx)

0๐Ÿ‘

โœ…

You may call the web service method from Jquery Ajax function and return the values.
What you have to change is

1) Change the return type of your web method to string[][](Array of string Arrays:because we need to return two arrays)

2) Call this web method with the help of Jquery ajax function and in the success function assign the data and label options with respective arrays received from the jquery ajax call.
documentation of Jquery ajax function

0๐Ÿ‘

Finally I solved it like this

 <script>

   //make an ajax call to the webservice
   //then use `chartlabel` as label and `chartData` as Data

    var chartLabel= [];
    var chartData= [];

    $.ajax({
        url: 'TestService.asmx/GetTotalPhoneSales',
        method: 'post',
        dataType: 'json',
        success: function (data) {

            $(data).each(function (index, item) {
                chartLabel.push(item.Phone);
                chartData.push(item.Amount);
            });

        },
        error: function (err) {
            alert(err);
        }
    });

   var config = {
        type: 'pie',
        data: {
            datasets: [{
                data: chartData,
                backgroundColor: [
                    "#3e95cd", "#8e5ea2", "#3cba9f"
                ],
                label: 'Labels'
            }],
            labels: chartLabel
        },
        options: {
            responsive: true
        }
    };

    window.onload = function () {
        var ctx = document.getElementById('chart-area').getContext('2d');
        window.myPie = new Chart(ctx, config);
    };
 </script>

Note: Its better to assign the backgroundColor programmatically, so that when new items are added to the database then those items will not show up with same color on the chart by default.
thanks for the hint @Gagan Deep

Leave a comment