locked
Chart.Js with webmethod and data from sql server RRS feed

  • Question

  • User2015884762 posted

    Hi

    I am new to the charting feature and web methods as well. Anyhow, I have googled and I managed to come up with this, it's not working at all. 

    Appreciate if someone can point out what I am missing. Basically, my data is in sql server and I am trying to pull the data into a pie..( just a test I am running before I move on the real project). I found the code at this link https://stackoverflow.com/questions/54884956/pie-chart-using-chart-js-and-asp-net-web-service-asmx - I modified it with the data in my sql..

    So this is the code. 

    This is the Chartnew.aspx page

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Chartnew.aspx.cs" Inherits="ChartTest.Chartnew" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
       
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script src="//cdn.jsdelivr.net/excanvas/r3/excanvas.js" type="text/javascript"></script>
         <script src="Scripts/Chart.js"></script>
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div id="canvas-holder" style="width:40%">
        <canvas id="chart-area"></canvas>
    </div>
        </form>
        <script src="Scripts/JavaScript.js"></script>
    </body>
    </html>
    

    This is the code behind page. 

    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Text;
    using System.Web;
    using System.Web.Script.Serialization;
    using System.Web.Services;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace ChartTest
    {
        public partial class Chartnew : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
    
            }
    
           
           
    
            [WebMethod]
            public void GetTotalPhoneSales()
            {
                string cs = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
                List<TotalSales> totalSales = new List<TotalSales>();
                using (SqlConnection con = new SqlConnection(cs))
                {
                    SqlCommand cmd = new SqlCommand("Sales by Year", con)
                    {
                        CommandType = CommandType.StoredProcedure
                    };
                    con.Open();
                    SqlDataReader rdr = cmd.ExecuteReader();
                    while (rdr.Read())
                    {
                        TotalSales PhoneSale = new TotalSales
                        {
                            Amount = Convert.ToDouble(rdr["Subtotal"]),
                            Year = Convert.ToInt32(rdr["Year"])
                        };
                        totalSales.Add(PhoneSale);
                    }
                }
                JavaScriptSerializer js = new JavaScriptSerializer();
                Context.Response.Write(js.Serialize(totalSales));
            }
        }
    
    
        class TotalSales
        {
            public double Amount;
            public int Year;
        }
    }

    This is the external JavaScript file.

    console.log('Hello');
    var chartLabel = [];
    var chartData = [];
    
    $.ajax({
        alert: ("It has ended"),
        url: 'Chartnew.aspx/GetTotalPhoneSales',
        method: 'post',
        dataType: 'json',
        
        success: function (data) {
    
            $(data).each(function (index, item) {
                chartLabel.push(item.Year);
                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);
    };
    Monday, April 5, 2021 4:07 AM

Answers

  • User-1330468790 posted

    Hi callykalpana,

     

    Thank you for providing codes which makes the troubleshooting more efficient.

    Actually, there are some mistakes in the codes.

    • Miss "static" in [WebMethod] of the code behind method.
    • Miss <contentType: "application/json; charset=utf-8"> in ajax parameter.
    • Put the codes "new Chart(ctx, config)" in a wrong place.
    • Wrongly return the result from [WebMethod].
    • Wrongly fetch data from success function.

     

    More details, you could refer to below codes.

    aspx:

     <form id="form1" runat="server">
            <div id="canvas-holder" style="width: 40%">
                <canvas id="chart-area"></canvas>
            </div>
        </form>
        <script>
            console.log('Hello');
            var chartLabel = [];
            var chartData = [];
    
            $.ajax({
                alert: ("It has ended"),
                url: 'Chartnew.aspx/GetTotalPhoneSales',
                method: 'post',
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    // Get json data from d, check it from dev-tools => Press F12
                    data = JSON.parse(data.d);
                    
                    $(data).each(function (index, item) {
                        chartLabel.push(item.Year);
                        chartData.push(item.Amount);
                    });
    
                    // Set the data from here
                    var config = {
                        type: 'pie',
                        data: {
                            datasets: [{
                                data: chartData,
                                backgroundColor: [
                                    "#3e95cd", "#8e5ea2", "#3cba9f"
                                ],
                                label: 'Labels'
                            }],
                            labels: chartLabel
                        },
                        options: {
                            responsive: true
                        }
                    };
    
                    // Initial Chart in ajax success function
                    var ctx = document.getElementById('chart-area').getContext('2d');
                    window.myPie = new Chart(ctx, config);
    
                },
                error: function (err) {
                    alert(err);
                }
            });
            
            window.onload = function () {
               
            };
        </script>

    Code behind: (Data Simulation)

    public partial class Chartnew : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
    
            }
    
            [WebMethod]
            public static string GetTotalPhoneSales()
            {
                List<TotalSales> totalSales = new List<TotalSales>();
    
                for (int i = 0; i < 3; i++) {
                    TotalSales PhoneSale = new TotalSales
                    {
                        Amount = Convert.ToDouble(i+100),
                        Year = Convert.ToInt32(i+2020)
                    };
                    totalSales.Add(PhoneSale);
                }
                
                JavaScriptSerializer js = new JavaScriptSerializer();
                
                return js.Serialize(totalSales);
            }
        }
    
        class TotalSales
        {
            public double Amount;
            public int Year;
        }

    Demo:

     

    Hope helps.

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, April 6, 2021 9:36 AM

All replies

  • User-1330468790 posted

    Hi callykalpana,

     

    Thank you for providing codes which makes the troubleshooting more efficient.

    Actually, there are some mistakes in the codes.

    • Miss "static" in [WebMethod] of the code behind method.
    • Miss <contentType: "application/json; charset=utf-8"> in ajax parameter.
    • Put the codes "new Chart(ctx, config)" in a wrong place.
    • Wrongly return the result from [WebMethod].
    • Wrongly fetch data from success function.

     

    More details, you could refer to below codes.

    aspx:

     <form id="form1" runat="server">
            <div id="canvas-holder" style="width: 40%">
                <canvas id="chart-area"></canvas>
            </div>
        </form>
        <script>
            console.log('Hello');
            var chartLabel = [];
            var chartData = [];
    
            $.ajax({
                alert: ("It has ended"),
                url: 'Chartnew.aspx/GetTotalPhoneSales',
                method: 'post',
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    // Get json data from d, check it from dev-tools => Press F12
                    data = JSON.parse(data.d);
                    
                    $(data).each(function (index, item) {
                        chartLabel.push(item.Year);
                        chartData.push(item.Amount);
                    });
    
                    // Set the data from here
                    var config = {
                        type: 'pie',
                        data: {
                            datasets: [{
                                data: chartData,
                                backgroundColor: [
                                    "#3e95cd", "#8e5ea2", "#3cba9f"
                                ],
                                label: 'Labels'
                            }],
                            labels: chartLabel
                        },
                        options: {
                            responsive: true
                        }
                    };
    
                    // Initial Chart in ajax success function
                    var ctx = document.getElementById('chart-area').getContext('2d');
                    window.myPie = new Chart(ctx, config);
    
                },
                error: function (err) {
                    alert(err);
                }
            });
            
            window.onload = function () {
               
            };
        </script>

    Code behind: (Data Simulation)

    public partial class Chartnew : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
    
            }
    
            [WebMethod]
            public static string GetTotalPhoneSales()
            {
                List<TotalSales> totalSales = new List<TotalSales>();
    
                for (int i = 0; i < 3; i++) {
                    TotalSales PhoneSale = new TotalSales
                    {
                        Amount = Convert.ToDouble(i+100),
                        Year = Convert.ToInt32(i+2020)
                    };
                    totalSales.Add(PhoneSale);
                }
                
                JavaScriptSerializer js = new JavaScriptSerializer();
                
                return js.Serialize(totalSales);
            }
        }
    
        class TotalSales
        {
            public double Amount;
            public int Year;
        }

    Demo:

     

    Hope helps.

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, April 6, 2021 9:36 AM
  • User2015884762 posted

    Thank you Sean Fang for pointing out the errors, I have marked yours as an answer.

    Wednesday, April 7, 2021 7:41 AM