2

I have seen this http://codepedia.info/chartjs-asp-net-create-pie-chart-with-database-calling-jquery-ajax-c/ link and followed every steps but dint get the output(i have used "public class cityPopulation") in code behind instead of asmx page will it be the error

</head>
<body>
    <script>
        function drawPieChart(seriesData) {

            $('#container').highcharts({
                chart: {
                    plotBackgroundColor: null,
                    plotBorderWidth: null,
                    plotShadow: false,
                    type: 'pie'
                },
                title: {
                    text: 'Population percentage city wise'
                },
                tooltip: {
                    pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
                },
                plotOptions: {
                    pie: {
                        allowPointSelect: true,
                        cursor: 'pointer',
                        dataLabels: {
                            enabled: true,
                            format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                            style: {
                                color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                            }
                        }
                    }
                },
                series: [{
                    name: "Brands",
                    colorByPoint: true,
                    data: seriesData
                }]
            });
        }
        $("#btnCreatePieChart").on('click', function (e) {
            var pData = [];
            pData[0] = $("#ddlyear").val();

            var jsonData = JSON.stringify({ pData: pData });

            $.ajax({
                type: "POST",
                url: "aspchartjsdemo.aspx/getCityPopulation",
                data: jsonData,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess_,
                error: OnErrorCall_
            });

            function OnSuccess_(response) {
                var aData = response.d;
                var arr = []

                $.map(aData, function (item, index) {
                    var i = [item.city_name, item.population];
                    var obj = {};
                    obj.name = item.city_name;
                    obj.y = item.population;
                    arr.push(obj);
                });
                var myJsonString = JSON.stringify(arr);
                var jsonArray = JSON.parse(JSON.stringify(arr));

                drawPieChart(jsonArray);

            }
            function OnErrorCall_(response) {
                alert("Whoops something went wrong!");
            }
            e.preventDefault();
        });
        </script>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="ddlyear" runat="server" >
            <asp:ListItem>2010</asp:ListItem>
            <asp:ListItem>2011</asp:ListItem>
            <asp:ListItem>2012</asp:ListItem>
        </asp:DropDownList>

        <asp:Button ID="btnCreatePieChart" runat="server" Text="Button" />

<br />
<div>
    <div id="container" style="width: 500px; height: 500px"></div>
</div>
    </div>
    </form>
</body>
</html>


here is my  Code Behind..Im Unable to Fetch the data from database.

    [WebMethod]
    public List<cityPopulation> getCityPopulation(List<string> pData)
    {
        List<cityPopulation> p = new List<cityPopulation>();

        using (NpgsqlConnection con = new NpgsqlConnection("Server=Localhost;Port=5432;User Id=postgres;Password=postgres;Database=database4;"))
        {
            string myQuery = "SELECT id_, city_name, population FROM  tb_city_population WHERE  year_of = @year";
            NpgsqlCommand cmd = new NpgsqlCommand();
            cmd.CommandText = myQuery;
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddWithValue("@year", pData[0]);
            cmd.Connection = con;
            con.Open();
            NpgsqlDataReader dr = cmd.ExecuteReader();
            if (dr.HasRows)
            {
                while (dr.Read())
                {
                    cityPopulation cpData = new cityPopulation();
                    cpData.city_name = dr["city_name"].ToString();
                    cpData.population = Convert.ToInt32(dr["population"].ToString());
                    p.Add(cpData);
                }
            }
        }
        return p;
    }

    public class cityPopulation
    {
        public string city_name { get; set; }
        public int population { get; set; }
        public string id { get; set; }
    }
Any Help Highly appreciated..
10
  • The bugs here is usually bad javascript render, or bad data format. See first of all if you have javascript errors on your console. Then fix them and continue with debugging what data you send. Commented Aug 10, 2016 at 8:03
  • Hi Aristos thanks for ur reply..I have seen the console but no bugs were found. Commented Aug 10, 2016 at 9:14
  • then debug your data to see what you send and how you input it to hightchart Commented Aug 10, 2016 at 9:20
  • Even i have done debugging but the control in not moving to the ajax call Commented Aug 10, 2016 at 9:48
  • How your JSON data does it look like ? Commented Aug 10, 2016 at 11:16

1 Answer 1

1

This is how I build the Pie:

<div id="pieChart"></div>

<script type="text/javascript" src="highcharts.js"></script>

<script>
    var myPieData = [ ['AAA', 34.03], ['BBB', 27.01], ['CCC', 18.77], ['DDD', 11.01], ['EEE', 5.91], ['FFF', 3.27] ];

    chart = new Highcharts.Chart({
        chart: {
            renderTo: 'pieChart',
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false
        },
        title: {
            text: 'My PieData'
        },
        tooltip: {
            pointFormat: '<b>{point.percentage:.2f}%</b>',
            percentageDecimals: 2
        },
        plotOptions: {
            pie: {
                allowPointSelect: false,
                cursor: 'default',
                dataLabels: {
                    enabled: false,
                    color: '#000000',
                    connectorColor: '#000000',
                    formatter: function () {
                        return '<b>' + this.point.name + '</b>: ' + this.percentage + ' %';
                    }
                }
            }
        },
        series: [{
            type: 'pie',
            name: '',
            data: myPieData
        }]
    });
</script>

The part you have to replace with your own data is [ ['Label A', 34.03], ['Label B', 27.01], ['Label C', 18.77], ['Label D', 11.01], ['Label E', 5.91], ['Label F', 3.27] ] Of course the total value of all the data should be 100.00%

You can do that with a Literal or a string that is filled with content from code behind: var myPieData = [ <%= pieData %> ] or get it from an external source.

Depending on your localization settings, a numeric value can contain a "," instead of a "." (23,59 or 23.59). If your localization uses a "," you will have to replace that with a dot.

UPDATE

As requested an example of how to get a correct string that you can use to build the pie. This should get you started... Just make sure that population is in percentages, not absolute numbers.

public string getCityPopulation(List<string> pData)
{
    StringBuilder sb = new StringBuilder();
    string myQuery = "SELECT city_name, population FROM tb_city_population WHERE (year_of = @year)";

    using (SqlConnection connection = new SqlConnection(Common.connectionString))
    using (SqlCommand command = new SqlCommand(myQuery, connection))
    {
        command.Parameters.AddWithValue("@year", pData[0]);
        try
        {
            connection.Open();
            SqlDataReader dr = command.ExecuteReader();
            if (dr.HasRows)
            {
                while (dr.Read())
                {
                    sb.Append("[");
                    sb.Append("'" + dr["city_name"].ToString() + "'");
                    sb.Append(", ");
                    sb.Append(dr["population"].ToString().Replace(",", "."));
                    sb.Append("],");
                }
            }
        }
        catch
        {
            //error connecting\reading the database
        }
    }

    return "[ " + sb.ToString().TrimEnd(',') + " ]";
}
Sign up to request clarification or add additional context in comments.

4 Comments

Hi VDWWD thanks for your reply..Actually im getting data from database and converting it to json. If any Example will be highly appriciated
Thanks VDWWD your code i think working fine but when i click the button as done in this tutorial link . There is no output .Can u please guide me where is going wrong , Thanks alor for ur help
Try to break up your problem into little pieces first. Start with making a page that the Ajax function calls to. When the call is made to that page it should only output a single string (no HTML etc). Then make sure that the string has the output like in my example by calling getCityPopulation and Response.Write the result. You can test that by opening that page in the browser. If that is successful try to get the Ajax call working from the Main page.
Thanks VDWWD for ur support ..I have found where i was going wrong

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.