Dynamically bind (populate) multiple google line chart using jQuery and AJAX in ASP.Net

sofia
 
on Jun 11, 2021 05:22 AM
Sample_173943.zip
2312 Views

hi sir,

i run the code of multiple google linechart in my webpages.

there are thousands of charts that i have to shown in my webpage and i have to call my javascript function (MakeAjaxCall('123.117.1526', $("#chart1")[0])) and give static ip address in this function. 

i want that may code should get ipaddress dynamically from database table and draw chart against every ipaddress automatically. i means if i update my database than there is no need to update my code.

i have an issue with my code that if i update/add my database table than i have to update my code again and again which is not suitable as well as numbers of line also too many.

please help me to solve my problem.

I Have two database table :

First table

Ipaddress            name

123.145.2. 3       room

123.145.6.677     hall

123.145.78.56     kitchen

123.145.34.78     ground

123.145.45.66     room2

Table 2

Ipaddress               pingtime                        status

123.145.2. 3           June 10, 2021 1:30AM          100

123.145.2. 3           June 10, 2021 5:30pm         75

123.145.2. 3           June 11, 2021 11:30AM        50

123.145.2. 3           June 11, 2021 2:30pm          0

123.145.6.677         June 10, 2021 1:30AM          100

123.145.6.677         June 10, 2021 4:00pM          50

123.145.6.677         June 11, 2021 2:30AM          100

123.145.6.677         June 10, 2021 8:30pM          100

I am using table 2 in my database query.

Java script

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
    google.load("visualization", "1", { packages: ["corechart"] });
    google.setOnLoadCallback(drawChart);
    function drawChart() {
        MakeAjaxCall("123.145.6.677", $("#chart")[0])
        MakeAjaxCall("123.145.2. 3",$("#chart2")[0])
        MakeAjaxCall("19.25.36.89", $("#chart3")[0])
        MakeAjaxCall("123.56.87.0", $("#chart4")[0])
        MakeAjaxCall("192.72.978.26", $("#chart5")[0])
        MakeAjaxCall("134.78.256", $("#chart6")[0])
        MakeAjaxCall("192.6.27.2", $("#chart7")[0])
        MakeAjaxCall("192.90.14.45", $("#chart8")[0])
    }

    function MakeAjaxCall(ipAddress, dvElement) {
        $.ajax({
            type: "POST",
            url: "graph.aspx/GetChartData",
            data: '{ipAddress:"' + ipAddress + '"}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (r) {
                var data = new google.visualization.DataTable();
                data.addColumn('date', 'pingtime');
                data.addColumn('number', 'ipstatus');
                for (var i = 0; i < r.d.length; i++) {
                    data.addRow([new Date(parseInt(r.d[i][0].substr(6))), parseInt(r.d[i][1])]);
                }

                var maxValue = Math.max.apply(Math, r.d.map(function (x) { return x[1]; }));
                var tick = [];
                for (var i = 0; i <= (maxValue / 25) + 1; i++) {
                    tick.push(i * 25);
                }

                var chart = new google.visualization.LineChart(dvElement);
                var options = {
                    title: 'ipaddress : ' + ipAddress,
                    width: 700,
                    height: 400,
                   
                    bar: { groupWidth: "95%" },
                    legend: { position: "none" },
                    isStacked: true,
                    vAxis: {
                        viewWindow: {
                            min: 0,
                            max: maxValue
                        },
                        ticks: tick,
                        title: 'IPSTATUS',
                        textStyle: {
                            fontStyle: "bold",
                            italic: true,
                            fontSize: 12,
                            color: '#0000FF'
                        },
                        titleTextStyle:{
                            fontStyle: "normal",
                            fontWeight: 'bold',
                            italic: true,
                            fontSize: 12,
                            color: '#0000FF'
                        }
                    },
                    hAxis: {
                        title: 'Time',
                        titleTextStyle:
                        {
                            fontStyle: "normal",
                            fontWeight: 'bold',
                            italic: true,
                            color: '#0000FF'
                        },                       
                    }
                };

                chart.draw(data, options);
            },
            failure: function (r) {
                alert(r.responsetext);
            },
            error: function (r) {
                alert(r.responsetext);
            }
        });
    }
</script>
<table>
    <tr> 
        <td><div id="chart" ></div></td>
        <td><div id="chart2" ></div></td>
        <td><div id="chart3" ></div></td>
        <td><div id="chart4" ></div></td>
    </tr>
    <tr>
        <td><div id="chart5" ></div></td>
        <td><div id="chart6" ></div></td>
        <td><div id="chart7" ></div></td>
        <td><div id="chart8" ></div></td>
    </tr>
</table>

C#

namespace NodesDetails
{
    public partial class graph : System.Web.UI.Page
    {
        [WebMethod]
        public static List<object> GetChartData(string ipAddress)
        {
            string query = string.Format("SELECT [pingtime],[ipstatus] FROM [dbo].[record] WHERE ipaddress='{0}' AND CONVERT(DATE,pingtime,103) BETWEEN CONVERT(DATE,DATEADD(DAY, -7, GETDATE()),103) AND CONVERT(DATE,GETDATE(),103) ORDER BY CONVERT(DATETIME,pingtime,103) ASC", ipAddress);
            string constr = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
            List<object> chartData = new List<object>();
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand(query))
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = con;
                    con.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            chartData.Add(new object[] { Convert.ToDateTime(sdr["pingtime"]), sdr["ipstatus"] });
                        }
                    }
                    con.Close();

                    return chartData;
                }
            }
        }
    }
}

please help me sir.

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Jun 12, 2021 01:35 AM

Hi sofia,

Check this example. Now please take its reference and correct your code.

HTML

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
    google.load("visualization", "1", { packages: ["corechart"] });
    google.setOnLoadCallback(drawChart);
    function drawChart() {
        $.ajax({
            type: "POST",
            url: "Default.aspx/GetIpAddress",
            data: {},
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (r) {
                for (var i = 0; i < r.d.length; i++) {
                    MakeAjaxCall(r.d[i], $("#chart" + (i + 1))[0]);
                }
            },
            failure: function (r) {
                alert(r.responsetext);
            },
            error: function (r) {
                alert(r.responsetext);
            }
        });
    }

    function MakeAjaxCall(ipAddress, dvElement) {
        $.ajax({
            type: "POST",
            url: "Default.aspx/GetChartData",
            data: '{ipAddress:"' + ipAddress + '"}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (r) {
                var data = new google.visualization.DataTable();
                data.addColumn('date', 'pingtime');
                data.addColumn('number', 'ipstatus');
                for (var i = 0; i < r.d.length; i++) {
                    data.addRow([new Date(parseInt(r.d[i][0].substr(6))), parseInt(r.d[i][1])]);
                }

                var maxValue = Math.max.apply(Math, r.d.map(function (x) { return x[1]; }));
                var tick = [];
                for (var i = 0; i <= (maxValue / 25) + 1; i++) {
                    tick.push(i * 25);
                }

                var chart = new google.visualization.LineChart(dvElement);
                var options = {
                    title: 'ipaddress : ' + ipAddress,
                    width: 400,
                    height: 400,
                    bar: { groupWidth: "95%" },
                    legend: { position: "none" },
                    isStacked: true,
                    vAxis: {
                        viewWindow: {
                            min: 0,
                            max: maxValue
                        },
                        ticks: tick,
                        title: 'IPSTATUS',
                        textStyle:
                        {
                            fontStyle: "bold",
                            italic: true,
                            fontSize: 12,
                            color: '#0000FF'
                        },
                        titleTextStyle:
                        {
                            fontStyle: "normal",
                            fontWeight: 'bold',
                            italic: true,
                            fontSize: 12,
                            color: '#0000FF'
                        }
                    },
                    hAxis: {
                        title: 'Time',
                        titleTextStyle:
                        {
                            fontStyle: "normal",
                            fontWeight: 'bold',
                            italic: true,
                            color: '#0000FF'
                        }
                    }
                };

                chart.draw(data, options);
            },
            failure: function (r) {
                alert(r.responseText);
            },
            error: function (r) {
                alert(r.responseText);
            }
        });
    }
</script>
<table>
    <tr>
        <td><div id="chart1"></div></td>
        <td><div id="chart2"></div></td>
        <td><div id="chart3"></div></td>
        <td><div id="chart4"></div></td>
    </tr>
    <tr>
        <td><div id="chart5"></div></td>
        <td><div id="chart6"></div></td>
        <td><div id="chart7"></div></td>
        <td><div id="chart8"></div></td>
    </tr>
</table>

Namespaces

C#

using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;

VB.Net

Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Services

Code

C#

[WebMethod]
public static List<object> GetChartData(string ipAddress)
{
    string query = string.Format("SELECT [pingtime],[ipstatus] FROM [dbo].[record] WHERE ipaddress='{0}' AND CONVERT(DATE,pingtime,103) BETWEEN CONVERT(DATE,DATEADD(DAY, -7, GETDATE()),103) AND CONVERT(DATE,GETDATE(),103) ORDER BY CONVERT(DATETIME,pingtime,103) ASC", ipAddress);
    string constr = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
    List<object> chartData = new List<object>();
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            con.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    chartData.Add(new object[] { Convert.ToDateTime(sdr["pingtime"]), sdr["ipstatus"] });
                }
            }
            con.Close();

            return chartData;
        }
    }
}

[WebMethod]
public static List<string> GetIpAddress()
{
    string query = "SELECT DISTINCT ipaddress FROM [dbo].[record]";
    string constr = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
    List<string> ips = new List<string>();
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            con.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    ips.Add(sdr["ipaddress"].ToString());
                }
            }
            con.Close();

            return ips;
        }
    }
}

VB.Net

<WebMethod>
Public Shared Function GetChartData(ByVal ipAddress As String) As List(Of Object)
    Dim query As String = String.Format("SELECT [pingtime],[ipstatus] FROM [dbo].[record] WHERE ipaddress='{0}' AND CONVERT(DATE,pingtime,103) BETWEEN CONVERT(DATE,DATEADD(DAY, -7, GETDATE()),103) AND CONVERT(DATE,GETDATE(),103) ORDER BY CONVERT(DATETIME,pingtime,103) ASC", ipAddress)
    Dim constr As String = ConfigurationManager.ConnectionStrings("dbcs").ConnectionString
    Dim chartData As List(Of Object) = New List(Of Object)()
    Using con As SqlConnection = New SqlConnection(constr)
        Using cmd As SqlCommand = New SqlCommand(query)
            cmd.CommandType = CommandType.Text
            cmd.Connection = con
            con.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                While sdr.Read()
                    chartData.Add(New Object() {Convert.ToDateTime(sdr("pingtime")), sdr("ipstatus")})
                End While
            End Using
            con.Close()

            Return chartData
        End Using
    End Using
End Function

<WebMethod>
Public Shared Function GetIpAddress() As List(Of String)
    Dim query As String = "SELECT DISTINCT ipaddress FROM [dbo].[record]"
    Dim constr As String = ConfigurationManager.ConnectionStrings("dbcs").ConnectionString
    Dim ips As List(Of String) = New List(Of String)()
    Using con As SqlConnection = New SqlConnection(constr)
        Using cmd As SqlCommand = New SqlCommand(query)
            cmd.CommandType = CommandType.Text
            cmd.Connection = con
            con.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                While sdr.Read()
                    ips.Add(sdr("ipaddress").ToString())
                End While
            End Using
            con.Close()

            Return ips
        End Using
    End Using
End Function

Screenshot