How can I generate real-time highchart from my database data?

I looked at the following links. Json binding leads to the creation of high-performance graphs for asp.net mvc 4 , high maps with mvc C # and sql , HighChart Demo and many others. However, I could not find a working demo showing how to implement highchart using data from a database.

Purpose: I want to create a graph in real time that receives data from my database. What I want is very similar to the third link, which provides in real time a high level with randomly generated values. This is also similar along the X axis and Y axis, since I want my X axis to be β€œTime” (I have a DateTime column in my database) and the y axis to be an integer (I have a variable for this a also in my database).

Please, I need help sending the model data to razor mode.

Note that I am already using SignalR to display the table in real time. I also want to know if it can be used automatically for automatic updates.

Below is the code snippet of my script in the view. I used the code shown in link 3 to generate highchart. Please tell me where I should apply the changes in my code.

@section Scripts{
        <script src="~/Scripts/jquery.signalR-2.2.0.js"></script>
        <!--Reference the autogenerated SignalR hub script. -->
        <script src="~/SignalR/Hubs"></script>

        <script type="text/javascript">
            $(document).ready(function () {
                // Declare a proxy to reference the hub.
                var notifications = $.connection.dataHub;

                //debugger;
                // Create a function that the hub can call to broadcast messages.
                notifications.client.updateMessages = function () {
                    getAllMessages()
                };
                // Start the connection.
                $.connection.hub.start().done(function () {
                    alert("connection started")
                    getAllMessages();
                }).fail(function (e) {
                    alert(e);
                });
                //Highchart
                Highcharts.setOptions({
                    global: {
                        useUTC: false
                    }
                });
                //Fill chart
                $('#container').highcharts({
                    chart: {
                        type: 'spline',
                        animation: Highcharts.svg, // don't animate in old IE
                        marginRight: 10,
                        events: {
                            load: function () {
                                // set up the updating of the chart each second
                                var series = this.series[0];
                                setInterval(function () {
                                    var x = (new Date()).getTime(), // current time
                                        y = Math.random();
                                    series.addPoint([x, y], true, true);
                                }, 1000);//300000
                            }
                        }
                    },
                    title: {
                        text: 'Live random data'
                    },
                    xAxis: {
                        type: 'datetime',
                        tickPixelInterval: 150
                    },
                    yAxis: {
                        title: {
                            text: 'Value'
                        },
                        plotLines: [{
                            value: 0,
                            width: 1,
                            color: '#808080'
                        }]
                    },
                    tooltip: {
                        formatter: function () {
                            return '<b>' + this.series.name + '</b><br/>' +
                                Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
                                Highcharts.numberFormat(this.y, 2);
                        }
                    },
                    legend: {
                        enabled: false
                    },
                    exporting: {
                        enabled: false
                    },
                    series: [{
                        name: 'Random data',
                        data: (function () {
                            // generate an array of random data
                            var data = [],
                                time = (new Date()).getTime(),
                                i;

                            for (i = -19; i <= 0; i += 1) {
                                data.push({
                                    x: time + i * 1000,
                                    y: Math.random()
                                });
                            }
                            return data;
                        }())
                    }]
                });

            });
            function getAllMessages() {
                var tbl = $('#messagesTable');
                var data = @Html.Raw(JsonConvert.SerializeObject(this.Model))

        $.ajax({
            url: '/home/GetMessages',
            data: {
                id: data.id,
            },
            contentType: 'application/html ; charset:utf-8',
            type: 'GET',
            dataType: 'html'

        }).success(function (result) {
            tbl.empty().append(result);
            $("#g_table").dataTable();
        }).error(function (e) {
            alert(e);
        });
            }
        </script>
    }

UPDATED CODE

//Highchart
Highcharts.setOptions({
global: {
   useUTC: false }
 });
//Fill chart
chart = new Highcharts.Chart({
chart: {
  renderTo: 'container',
  defaultSeriesType: 'spline',
  events: {
      load:  $.connection.hub.start().done(function () {
      alert("Chart connection started")
      var point = getAllMessagesforChart();
      var series = this.series[0];
      setInterval(function (point) {

         // add the point
         series.addPoint([point.date_time, point.my_value], true, true)

         }, 1000);
           }).fail(function (e) {
                   alert(e);
                               })
                           }
                        }
        title: {
        text: 'Live random data'
                   },
        xAxis: {
        type: 'datetime',
        tickPixelInterval: 150,
        maxZoom: 20 * 1000
                        },
        yAxis: {
        minPadding: 0.2,
        maxPadding: 0.2,
        title: {
            text: 'Value',
            margin: 80
                           }
                       },
        series: [{
              name: 'Random data',
              data: []
                       }]
                    });


function getAllMessagesforChart() {
                var data = @Html.Raw(JsonConvert.SerializeObject(this.Model))

        $.ajax({
            url: '/home/GetMessagesforChat',
            data: {
                id: data.id,
            },
            contentType: 'application/html ; charset:utf-8',
            type: 'GET',
            dataType: 'html'

        }).success(function (data) {
            data = JSON.parse(data);
            //data_graph = [].concat(data);
            //$("#debug").html(data_graph);

        }).error(function (e) {
            alert(e);
        });

                return data;
                //return data_graph;

}

+4
source share
1 answer

Here is an example that might help you:

http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/line-ajax/

it uses ajax callback function.

Well, you can also see my sample, where I add a row dynamically by clicking the add button.

http://plnkr.co/edit/Sh71yN?p=preview

You only need to add data to the desired structure.

Look at the function

$("#btnAdd").click(function()

of my script.js code

Hope this helps. Regards, Louis

0
source

Source: https://habr.com/ru/post/1584981/


All Articles