Populate (Bind) AMcharts 4 from database using jQuery AJAX in ASP.Net

Last Reply one month ago By dharmendr

Posted one month ago

Hi,

How to populate AMcharts 4 with SQL Server DB using webmethod in webforms

I need help populating the new version of AMCHARTS 4 with webmethod for webforms:

Thank you!

<script>
am4core.ready(function () {       
// Themes begin
am4core.useTheme(am4themes_animated);
// Themes end
var chart = am4core.create('chartdiv', am4charts.XYChart)
chart.colors.step = 2;

chart.legend = new am4charts.Legend()
chart.legend.position = 'top'
chart.legend.paddingBottom = 20
chart.legend.labels.template.maxWidth = 95

var xAxis = chart.xAxes.push(new am4charts.CategoryAxis())
xAxis.dataFields.category = 'category'
xAxis.renderer.cellStartLocation = 0.1
xAxis.renderer.cellEndLocation = 0.9
xAxis.renderer.grid.template.location = 0;

var yAxis = chart.yAxes.push(new am4charts.ValueAxis());
yAxis.min = 0;

function createSeries(value, name) {
    var series = chart.series.push(new am4charts.ColumnSeries())
    series.dataFields.valueY = value
    series.dataFields.categoryX = 'category'
    series.name = name

    series.events.on("hidden", arrangeColumns);
    series.events.on("shown", arrangeColumns);

    var bullet = series.bullets.push(new am4charts.LabelBullet())
    bullet.interactionsEnabled = false
    bullet.dy = 30;
    bullet.label.text = '{valueY}'
    bullet.label.fill = am4core.color('#ffffff')

    return series;
}

chart.data = [
    {
        category: 'Place #1',
        first: 22,
        second: 55,
        third: 60,
        fourth: 28
    },
    {
        category: 'Place #2',
        first: 30,
        second: 78,
        third: 69,
        fourth: 28
    },
    {
        category: 'Place #3',
        first: 27,
        second: 40,
        third: 45,
        fourth: 0
    },
    {
        category: 'Place #4',
        first: 50,
        second: 33,
        third: 22,
         fourth: 0
    }
]

createSeries('first', 'The First');
createSeries('second', 'The Second');
createSeries('third', 'The Third');
createSeries('fourth', 'The Fourth');

function arrangeColumns() {

    var series = chart.series.getIndex(0);

    var w = 1 - xAxis.renderer.cellStartLocation - (1 - xAxis.renderer.cellEndLocation);
    if (series.dataItems.length > 1) {
        var x0 = xAxis.getX(series.dataItems.getIndex(0), "categoryX");
        var x1 = xAxis.getX(series.dataItems.getIndex(1), "categoryX");
        var delta = ((x1 - x0) / chart.series.length) * w;
        if (am4core.isNumber(delta)) {
            var middle = chart.series.length / 2;

            var newIndex = 0;
            chart.series.each(function(series) {
                if (!series.isHidden && !series.isHiding) {
                    series.dummyData = newIndex;
                    newIndex++;
                }
                else {
                    series.dummyData = chart.series.indexOf(series);
                }
            })
            var visibleCount = newIndex;
            var newMiddle = visibleCount / 2;

            chart.series.each(function(series) {
                var trueIndex = chart.series.indexOf(series);
                var newIndex = series.dummyData;

                var dx = (newIndex - trueIndex + middle - newMiddle) * delta

                series.animate({ property: "dx", to: dx }, series.interpolationDuration, series.interpolationEasing);
                series.bulletsContainer.animate({ property: "dx", to: dx }, series.interpolationDuration, series.interpolationEasing);
            })
        }
    }
}

setTimeout(arguments.callee, 10000);      

});
</script>

 

<WebMethod>
Public Shared Function GetData() As List(Of ChartDetails)
    Dim Constring As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString.ToString()
   
    Using con As SqlConnection = New SqlConnection(Constring)
        Dim dataList As List(Of ChartDetails) = New List(Of ChartDetails)()
        Dim cmd As SqlCommand = New SqlCommand("SELECT Adults, [Peds], [when] FROM [ERDASH].[dbo].[Volume_Medians_Final]", con)
        cmd.CommandTimeout = 50
        cmd.CommandType = CommandType.Text
        con.Open()
        Dim da As SqlDataAdapter = New SqlDataAdapter(cmd)
        da.SelectCommand = cmd
        Dim dt As DataTable = New DataTable()
        da.Fill(dt)
        con.Close()

        For Each dtrow As DataRow In dt.Rows
            Dim details As ChartDetails = New ChartDetails()
            details.[when] = dtrow(2).ToString()
            details.Adults = dtrow(0).ToString()
            details.Peds = dtrow(1).ToString()
            dataList.Add(details)
        Next

    Return dataList
    End Using
 End Function

 Public Class ChartDetails
     Public Property [when] As String
     Public Property date1 As String
     Public Property Adults As String
     Public Property Peds As String
 End Class
<script src="https://cdn.amcharts.com/lib/4/core.js"></script>
<script src="https://cdn.amcharts.com/lib/4/charts.js"></script>
<script src="https://cdn.amcharts.com/lib/4/themes/material.js"></script>
<script src="https://cdn.amcharts.com/lib/4/lang/de_DE.js"></script>
<script src="https://cdn.amcharts.com/lib/4/geodata/germanyLow.js"></script>
<script src="https://cdn.amcharts.com/lib/4/fonts/notosans-sc.js"></script>
<!-- Resources -->
<script src="https://cdn.amcharts.com/lib/4/core.js"></script>
<script src="https://cdn.amcharts.com/lib/4/charts.js"></script>
<script src="https://cdn.amcharts.com/lib/4/themes/animated.js"></script>
<style>
    #chartdiv {
        width: 100%;
        height: 500px;
    }
</style>
<div id="chartdiv"></div>

 

Posted one month ago

Hi gkoutsiv,

Refer below sample. Bind the data from database instead of temporary list.

HTML

<div id="chartdiv"></div>
<script type="text/javascript" src="https://cdn.amcharts.com/lib/4/core.js"></script>
<script type="text/javascript" src="https://cdn.amcharts.com/lib/4/charts.js"></script>
<script type="text/javascript" src="https://cdn.amcharts.com/lib/4/themes/material.js"></script>
<script type="text/javascript" src="https://cdn.amcharts.com/lib/4/lang/de_DE.js"></script>
<script type="text/javascript" src="https://cdn.amcharts.com/lib/4/geodata/germanyLow.js"></script>
<script type="text/javascript" src="https://cdn.amcharts.com/lib/4/fonts/notosans-sc.js"></script>
<script type="text/javascript" src="https://cdn.amcharts.com/lib/4/themes/animated.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<style>
    #chartdiv {
        width: 100%;
        height: 500px;
    }
</style>
<script type="text/javascript">
    var data;
    $(function () {
        $.ajax({
            type: "POST",
            url: 'Default.aspx/GetData',
            data: {},
            contentType: "application/json; charset=utf-8",
            dataType: "text",
            success: function (r) {
                data = JSON.parse(r).d;
                am4core.useTheme(am4themes_animated);
                var chart = am4core.create('chartdiv', am4charts.XYChart)
                chart.colors.step = 2;
                chart.legend = new am4charts.Legend()
                chart.legend.position = 'top'
                chart.legend.paddingBottom = 20
                chart.legend.labels.template.maxWidth = 95

                var xAxis = chart.xAxes.push(new am4charts.CategoryAxis())
                xAxis.dataFields.category = 'category'
                xAxis.renderer.cellStartLocation = 0.1
                xAxis.renderer.cellEndLocation = 0.9
                xAxis.renderer.grid.template.location = 0;

                var yAxis = chart.yAxes.push(new am4charts.ValueAxis());
                yAxis.min = 0;

                function createSeries(value, name) {
                    var series = chart.series.push(new am4charts.ColumnSeries())
                    series.dataFields.valueY = value
                    series.dataFields.categoryX = 'category'
                    series.name = name

                    series.events.on("hidden", arrangeColumns);
                    series.events.on("shown", arrangeColumns);

                    var bullet = series.bullets.push(new am4charts.LabelBullet())
                    bullet.interactionsEnabled = false
                    bullet.dy = 30;
                    bullet.label.text = '{valueY}'
                    bullet.label.fill = am4core.color('#ffffff')

                    return series;
                }

                chart.data = data;
                createSeries('first', 'First');
                createSeries('second', 'Second');
                createSeries('third', 'Third');
                createSeries('fourth', 'Fourth');

                function arrangeColumns() {
                    var series = chart.series.getIndex(0);
                    var w = 1 - xAxis.renderer.cellStartLocation - (1 - xAxis.renderer.cellEndLocation);
                    if (series.dataItems.length > 1) {
                        var x0 = xAxis.getX(series.dataItems.getIndex(0), "categoryX");
                        var x1 = xAxis.getX(series.dataItems.getIndex(1), "categoryX");
                        var delta = ((x1 - x0) / chart.series.length) * w;
                        if (am4core.isNumber(delta)) {
                            var middle = chart.series.length / 2;

                            var newIndex = 0;
                            chart.series.each(function (series) {
                                if (!series.isHidden && !series.isHiding) {
                                    series.dummyData = newIndex;
                                    newIndex++;
                                }
                                else {
                                    series.dummyData = chart.series.indexOf(series);
                                }
                            })
                            var visibleCount = newIndex;
                            var newMiddle = visibleCount / 2;

                            chart.series.each(function (series) {
                                var trueIndex = chart.series.indexOf(series);
                                var newIndex = series.dummyData;

                                var dx = (newIndex - trueIndex + middle - newMiddle) * delta

                                series.animate({ property: "dx", to: dx }, series.interpolationDuration, series.interpolationEasing);
                                series.bulletsContainer.animate({ property: "dx", to: dx }, series.interpolationDuration, series.interpolationEasing);
                            })
                        }
                    }
                }

                arguments.callee;
            }
        });
    })
</script>

Code

C#

[System.Web.Services.WebMethod]
public static List<ChartDetails> GetData()
{
    List<ChartDetails> dataList = new List<ChartDetails>();
    dataList.Add(new ChartDetails { category = "Place #1", first = 22, second = 55, third = 60, fourth = 28 });
    dataList.Add(new ChartDetails { category = "Place #2", first = 30, second = 78, third = 69, fourth = 28 });
    dataList.Add(new ChartDetails { category = "Place #3", first = 27, second = 40, third = 45, fourth = 00 });
    dataList.Add(new ChartDetails { category = "Place #4", first = 50, second = 33, third = 22, fourth = 00 });

    return dataList;
}

public class ChartDetails
{
    public string category { get; set; }
    public int first { get; set; }
    public int second { get; set; }
    public int third { get; set; }
    public int fourth { get; set; }
}

VB.Net

<Services.WebMethod>
Public Shared Function GetData() As List(Of ChartDetails)
    Dim dataList As List(Of ChartDetails) = New List(Of ChartDetails)()
    dataList.Add(New ChartDetails With {.category = "Place #1", .first = 22, .second = 55, .third = 60, .fourth = 28})
    dataList.Add(New ChartDetails With {.category = "Place #2", .first = 30, .second = 78, .third = 69, .fourth = 28})
    dataList.Add(New ChartDetails With {.category = "Place #3", .first = 27, .second = 40, .third = 45, .fourth = 0})
    dataList.Add(New ChartDetails With {.category = "Place #4", .first = 50, .second = 33, .third = 22, .fourth = 0})
    Return dataList
End Function

Public Class ChartDetails
    Public Property category As String
    Public Property first As Integer
    Public Property second As Integer
    Public Property third As Integer
    Public Property fourth As Integer
End Class

Screenshot