0

I want to show the data on charts and i am using dotnet highcharts for it For now i am able to pass data from controller to the view using JavaScript and the data is displaying accordingly but when i insert data or DB is updated i always have to refresh the page, but i want to display data whenever DB is updated on run-time.

I have gone through many searches and i found that using ajax i can be able to perform my certain task

i have found this piece of ajax

   $.ajax({
type: "POST",
url: "update_visits_chart",
data: {month: month},
dataType: 'json',
success: function(data){
    options.series[0].setData(data);
}

here i have a question i have multiple arrays with different names as shown bellow

var myArrayX_kwh = [];
        var myArrayY_kwh = [];
        var myArrayY_power = [];
        var myArrayY_voltage_1 = [];
        var myArrayY_voltage_2 = [];
        var myArrayY_voltage_3 = [];
        var myArrayY_current_1 = [];
        var myArrayY_current_2 = [];
        var myArrayY_current_3 = [];

        var arry_kwh = [];
        var arry_power = [];
        var arry_voltage_1 = [];
        var arry_voltage_2 = [];
        var arry_voltage_3 = [];
        var arry_current_1 = [];
        var arry_current_2 = [];
        var arry_current_3 = [];


    @foreach (var st in ViewData["Meter_datetime"] as List<double?>)
        {
        @:myArrayX_kwh.push(@st);
    }

    @foreach (var st in ViewData["energy_kwh"] as List<double?>)
    {
        @:myArrayY_kwh.push(@st);
    }
    @foreach (var st in ViewData["power_kw"] as List<double?>)
    {
        @:myArrayY_power.push(@st);
    }
    @foreach (var st in ViewData["voltage_1"] as List<double?>)
    {
        @:myArrayY_voltage_1.push(@st);
    }
    @foreach (var st in ViewData["voltage_2"] as List<double?>)
    {
        @:myArrayY_voltage_2.push(@st);
    }
    @foreach (var st in ViewData["voltage_3"] as List<double?>)
    {
        @:myArrayY_voltage_3.push(@st);
    }
    @foreach (var st in ViewData["current_1"] as List<double?>)
    {
        @:myArrayY_current_1.push(@st);
    }
    @foreach (var st in ViewData["current_2"] as List<double?>)
    {
        @:myArrayY_current_2.push(@st);
    } @foreach (var st in ViewData["current_3"] as List<double?>)
     {
      @:myArrayY_current_3.push(@st);
    }


    for (var i = 0; i < myArrayX_kwh.length; i++) {
        arry_kwh.push({ x: myArrayX_kwh[i], y: myArrayY_kwh[i], });
        arry_power.push({ x: myArrayX_kwh[i], y: myArrayY_power[i], });
        arry_voltage_1.push({ x: myArrayX_kwh[i], y: myArrayY_voltage_1[i], });
        arry_voltage_2.push({ x: myArrayX_kwh[i], y: myArrayY_voltage_2[i], });
        arry_voltage_3.push({ x: myArrayX_kwh[i], y: myArrayY_voltage_3[i], });
        arry_current_1.push({ x: myArrayX_kwh[i], y: myArrayY_current_1[i], });
        arry_current_2.push({ x: myArrayX_kwh[i], y: myArrayY_current_2[i], });
        arry_current_3.push({ x: myArrayX_kwh[i], y: myArrayY_current_3[i], });
    }

how to pass them in ajax data field ? Any help will be appreciated

2 Answers2

0

You can do something like this :

    var myArrayX_kwh = [];
    var myArrayY_kwh = [];
    var myArrayY_power = [];
    var myArrayY_voltage_1 = [];
    var myArrayY_voltage_2 = [];
    var myArrayY_voltage_3 = [];
    var myArrayY_current_1 = [];
    var myArrayY_current_2 = [];
    var myArrayY_current_3 = [];

    var arry_kwh = [];
    var arry_power = [];
    var arry_voltage_1 = [];
    var arry_voltage_2 = [];
    var arry_voltage_3 = [];
    var arry_current_1 = [];
    var arry_current_2 = [];
    var arry_current_3 = [];


@foreach (var st in ViewData["Meter_datetime"] as List<double?>)
    {
    @:myArrayX_kwh.push(@st);
}

@foreach (var st in ViewData["energy_kwh"] as List<double?>)
{
    @:myArrayY_kwh.push(@st);
}
@foreach (var st in ViewData["power_kw"] as List<double?>)
{
    @:myArrayY_power.push(@st);
}
@foreach (var st in ViewData["voltage_1"] as List<double?>)
{
    @:myArrayY_voltage_1.push(@st);
}
@foreach (var st in ViewData["voltage_2"] as List<double?>)
{
    @:myArrayY_voltage_2.push(@st);
}
@foreach (var st in ViewData["voltage_3"] as List<double?>)
{
    @:myArrayY_voltage_3.push(@st);
}
@foreach (var st in ViewData["current_1"] as List<double?>)
{
    @:myArrayY_current_1.push(@st);
}
@foreach (var st in ViewData["current_2"] as List<double?>)
{
    @:myArrayY_current_2.push(@st);
} @foreach (var st in ViewData["current_3"] as List<double?>)
 {
  @:myArrayY_current_3.push(@st);
}


for (var i = 0; i < myArrayX_kwh.length; i++) {
    arry_kwh.push({ x: myArrayX_kwh[i], y: myArrayY_kwh[i], });
    arry_power.push({ x: myArrayX_kwh[i], y: myArrayY_power[i], });
    arry_voltage_1.push({ x: myArrayX_kwh[i], y: myArrayY_voltage_1[i], });
    arry_voltage_2.push({ x: myArrayX_kwh[i], y: myArrayY_voltage_2[i], });
    arry_voltage_3.push({ x: myArrayX_kwh[i], y: myArrayY_voltage_3[i], });
    arry_current_1.push({ x: myArrayX_kwh[i], y: myArrayY_current_1[i], });
    arry_current_2.push({ x: myArrayX_kwh[i], y: myArrayY_current_2[i], });
    arry_current_3.push({ x: myArrayX_kwh[i], y: myArrayY_current_3[i], });
}

}

For updating charts after some interval you can use following code :

var interval = window.setInterval(ajaxMethodCall, 20000);

above code will make ajax call after every 20 secs.

Using Polling :

$(document).ready(function poll() {
        setTimeout(function() {
            $.ajax({
                url : "/Test/TestServlet",
                type : "GET",
                //dataType : "json",
                //data : dataArray,

                success : function(data) {
                    alert("success")
                    dt.setValue(data.value);
            var chart2 = new Highcharts.Chart({

            chart: {
                renderTo: 'container2',
                zoomType: 'xy',
                resetZoomButton: {
                    position: {
                        align: 'right', // by default
                        verticalAlign: 'top', // by default
                        x: -250,
                        y: 5,
                        //height: 25
                    },

                    relativeTo: 'chart'
                }
            },
            title: {
                text: 'Power vs Date & Time',
                style: {
                    //color: '#FF00FF',
                    fontWeight: 'bold'
                }
            },
            xAxis: {
                // categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
                type: 'datetime'
            },
            yAxis: {
                title: {
                    text: 'Power (KW)'
                }

            },
            plotOptions: {  
                series: {
                    marker: {
                        enabled: true,
                        symbol: 'circle',
                        radius: 3
                    }
                }
            },
            series: [{
                    name : 'Power kW',
                    data: arry_power,
            }],

        });

                },
                error : function(data) {
                    console.log("error polling");
                },
                complete : poll,
            })
        }, 5000);
    });

here it is for one chart

 var chart2 = new Highcharts.Chart({

            chart: {
                renderTo: 'container2',
                zoomType: 'xy',
                resetZoomButton: {
                    position: {
                        align: 'right', // by default
                        verticalAlign: 'top', // by default
                        x: -250,
                        y: 5,
                        //height: 25
                    },

                    relativeTo: 'chart'
                }
            },
            title: {
                text: 'Power vs Date & Time',
                style: {
                    //color: '#FF00FF',
                    fontWeight: 'bold'
                }
            },
            xAxis: {
                // categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
                type: 'datetime'
            },
            yAxis: {
                title: {
                    text: 'Power (KW)'
                }

            },
            plotOptions: {  
                series: {
                    marker: {
                        enabled: true,
                        symbol: 'circle',
                        radius: 3
                    }
                }
            },
            series: [{
                    name : 'Power kW',
                    data: arry_power,
            }],

        });
Abhijeet
  • 4,069
  • 1
  • 22
  • 38
  • i have tried your method and i have done this $.ajax({ type: "POST", url: "Home/MultiGraph", data: dataArray, dataType: 'json', sussces: function (data) { for (var i = 0; i < 3; i++) { options.series[i].setData(data); } } }); but still unable to get any thing i still have to refresh my page to view updated data i have 4 charts in my view so i added a loop in which i have passed my data having dataArray –  Sep 01 '16 at 06:27
  • If you want to make update call after some interval you can refer new edited code. Which is very simple. Just replace ajaxMethodCall with respective ajax call – Abhijeet Sep 01 '16 at 09:28
  • what about polling ? i am using this (function poll() { setTimeout(function () { $.ajax({ url: "/Home/MultiGraph", type: "GET", success: function (dataArray) { console.log("polling"); }, dataType: "json", complete: poll, }) }, 5000); }); –  Sep 01 '16 at 10:23
  • Why don't you try above mentioned code for now and let me know. I will get back to you on poll. – Abhijeet Sep 01 '16 at 12:24
  • tried but nothing happens i might be missing something –  Sep 01 '16 at 12:29
  • Try the new code and let me know if it's working or not. I tried from my side, It's working perfectly for me – Abhijeet Sep 01 '16 at 12:43
  • What is you error?? Error Description? Can you explain what you want to do? Are you able to make ajax call – Abhijeet Sep 01 '16 at 13:26
  • no error is shown also i have tried this $.getJSON(url, data, success); following this article http://stackoverflow.com/questions/12223972/load-data-into-highcharts-with-ajax but no use –  Sep 01 '16 at 13:26
  • Explain me what you want? I will try to give you some basic code template – Abhijeet Sep 01 '16 at 13:28
  • all i want is whenever the database is updated the data on the charts will be shown automatically (if i am on the charts view ). till now i am able to view updated data when i refresh the page but i want it show automatically –  Sep 01 '16 at 13:35
  • Then use polling method with ajax mentioned above. you can check your browser console for every call output. You can also print on server console some data to check if you are able to call MultiGraph page properly – Abhijeet Sep 01 '16 at 13:38
  • The ajax code written by you can you give it to me. I will convert it into polling – Abhijeet Sep 01 '16 at 13:40
  • ok here it is i have followed the following example with slight modifications https://gist.github.com/jasdeepkhalsa/4353139/1aa5ad9ed61ba22c3e8f8dfc42eea2bd73bd66f8#file-recursivepolling-js –  Sep 01 '16 at 13:44
  • (function poll() { setTimeout(function () { $.ajax({ type: "POST", url: "/Home/MultiGraph/", //dataType: "json", success: function (data) { alert("success") dt.setValue(data.value); }, }); poll(); }, 5000); })(); –  Sep 01 '16 at 13:45
  • by commenting dataType i am able to see success message i have changed the name of dataArray to dt –  Sep 01 '16 at 13:45
  • I have changed AJAX call according to your use for polling just replace your code with this. I will work – Abhijeet Sep 01 '16 at 13:50
  • but from where the data is coming from then ? –  Sep 01 '16 at 13:51
  • data of success method will contain response from server – Abhijeet Sep 01 '16 at 13:51
  • it only shows success message for one time only after that when i update my DB nothing happens :( –  Sep 01 '16 at 13:57
  • It will show success message for every 5 sec. After every 5 sec, a call to your URL made by poll/ajax. You can write something on your server console to check the call made by ajax/poll. Data will refresh every 5 sec. – Abhijeet Sep 01 '16 at 13:59
  • On which browser console your checking the output – Abhijeet Sep 01 '16 at 14:01
  • chrome the ajax code which i provided you is showing me success message every 5 seconds –  Sep 01 '16 at 14:04
  • Well that's the output for ajax/poll call. Do you need anything else? – Abhijeet Sep 01 '16 at 14:04
  • yes butt it's not showing me the updated data it's just showing me the success message –  Sep 01 '16 at 14:06
  • the chart is still updating when i refresh the page i want it to show updated data without refreshing –  Sep 01 '16 at 14:07
  • Where is your HighChart related code.Call that code using polling and ajax. Give me your highchart related code – Abhijeet Sep 01 '16 at 14:07
  • in controller i have set all the data in viewdata and passed them into the view then i have initialized the charts in view and i am using 4 different charts in one view and they all should be updated automatically without refreshing the page –  Sep 01 '16 at 14:10
  • You have to call initialization of view using poll – Abhijeet Sep 01 '16 at 14:11
  • You can add this code in success function of your ajax call. It will create your chart for every 5 secs – Abhijeet Sep 01 '16 at 14:17
  • not possible as it will remove the chart from the view –  Sep 01 '16 at 14:21
  • declare chart2 outside ajax call and initialize it in ajax success method – Abhijeet Sep 01 '16 at 14:22
  • all the chart initialization is out side the ajax/poll call –  Sep 01 '16 at 14:24
  • just call chart initialization function in ajax – Abhijeet Sep 01 '16 at 14:25
  • Have you got the output? – Abhijeet Sep 01 '16 at 14:34
  • i have tried but the code is not running as it disappears the charts from the view –  Sep 01 '16 at 14:34
  • there is no success message and it just show me empty view without charts –  Sep 01 '16 at 14:35
  • Let me know when you post new question with updated code. Add code related to chart and ajax call – Abhijeet Sep 01 '16 at 14:42
  • As I'm going offline for now. I will answer you question tomorrow.And dont forget to post your new question here. – Abhijeet Sep 01 '16 at 14:54
  • I have posted a new question with details please goto this link http://stackoverflow.com/questions/39285852/unable-to-pass-json-data-into-ajax-success-call-in-asp-net-mvc –  Sep 02 '16 at 06:41
  • I will look into it. – Abhijeet Sep 02 '16 at 06:50
0

If you need real-time data updates then I would suggest a SignalR library. As stated on the official page:

SignalR allows bi-directional communication between server and client. Servers can now push content to connected clients instantly as it becomes available

You will simply wait for database change notification and push the updated data back to client and update the highcharts.

Tutorial #1

Tutorial #2

Ivan Sivak
  • 7,178
  • 3
  • 36
  • 42