Juniuz Juniuz - 7 months ago 45
Ajax Question

Highcharts doesn't display data

I'm a newbie in using Highcharts. I created a sample ASP.NET MVC application to create a line graph out of a json data returned from my controller into my view page. Also, I used ajax to get the data for the chart via success callback function.

This is the structure of the data (sample 4 rows of type TagTimeValue in a List)

private List<TagTimeValue> GetTagTimeValues()
{
var tagTimeValues = new List<TagTimeValue>
{
new TagTimeValue { ID=1, Name="CDT158", Value="23.9483", Time="04/01/2017", Good="true", Questionable="No", Units="vol", Substituted="not"},
new TagTimeValue { ID=2, Name="CDT158", Value="24.1183", Time="04/02/2017", Good="true", Questionable="No", Units="vol", Substituted="not"},
new TagTimeValue { ID=3, Name="CDT158", Value="25.2383", Time="04/03/2017", Good="false", Questionable="yes", Units="vol", Substituted="not"},
new TagTimeValue { ID=4, Name="CDT158", Value="25.6713", Time="04/04/2017", Good="false", Questionable="yes", Units="vol", Substituted="not"}
};

return tagTimeValues;
}


This is the method invoked by ajax call

public ActionResult UpdateTrend()
{
var values = GetTagTimeValues();
return Json(values, JsonRequestBehavior.AllowGet);
}


The script that invoke
UpdateTrend()
via ajax call in
Index.cshtml


$(document).ready(function () {
$.ajax({
url: "/home/UpdateTrend",
type: 'GET',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
cache: false
}).success(function (dataChart) {
var Xaxis = [];
var dataSeries = [];

for (var i = 0; i < dataChart.length; i++) {
var items = dataChart[i];
var XcategoriesItem = items.Time;
var seriesData = items.Value;

Xaxis.push(XcategoriesItem);
dataSeries.push(seriesData);
}

console.log(dataSeries);
getChart(Xaxis, dataSeries);

}).error(function (er, xhr, e) {
console.log("Error: ", er, xhr, e);
})
});


And, the
getChart
function

function getChart(Xaxis, dataseries)
{
var myChart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line'
},
title: {
text: 'Alarms/Events Chart'
},
plotOptions: {
series: {
dataLabels: {
enabled: true,
format: '{y}%'
}
}
},
xAxis: {
type: 'datetime',
title: {
text: 'Time'
},
categories: Xaxis
},
yAxis: {
title: {
text: 'Value'
}
},
series: dataseries
});
};


where it renders the chart to the
<div id="container" style="width:100%; height: 500px;"></div>
with an
id
of container.

Based on the scripts, I want my chart to have an x-axis of Time and, y-axis of value as series. But, when I run the application, there's no data displayed (screenshot below).

enter image description here

I also checked the json data in Google's chrome
console
panel, which I can see an array of
Time
(x-axis) and
Value
(series) parsed successfully.
enter image description here

Is there a missing configuration in my chart that wouldn't allow to display the series? Or, does my chart script is wrong?

I googled for similar issues, and I found heaps of possible solutions but, quite confused which one should I follow.

Any help is greatly appreciated.

Answer Source

Since posting this question, I don't have knowledge in Highchart. After 2 weeks of researched and using the library, I have learned basic configuration that will display data in the chart. For the benefit of other developers who seek help or just starting using Highchart, this is how I implement it.

ajax call to fetch data from the server and plot onto the chart

    function plotTrendData(data)
{
    $.ajax({
        type: 'GET',
        url: '/your url goes here/',
        data: { requestData: data },
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        success: function (data)
        {
            if (data.length > 4) {
                prepareChartData(data);
                if (myChart === null) {
                    plotChartData(dataSeries, xTitle);
                }
                else {
                    addChartSeries(dataSeries, xTitle);
                }
            }
        }
    });
}

function that prepares chart data (dataChart paramater contains the json data)

    function prepareChartData(dataChart)
{
    if (dataSeries.length > 0) dataSeries = [];
    for (var i = 0; i < dataChart.length; i++)
    {
        var items = dataChart[i];
        var xDate = +moment(items.Time);
        var seriesData = parseFloat(items.Value);

        dataSeries.push([xDate, seriesData]);
        xTitle = items.Name;
    }
}

function that add series onto an existing chart (for multiple series chart)

    function addChartSeries(dataSeries, xTitle)
{
    myChart.addSeries({
        name: xTitle,
        data: dataSeries
    });
}

And, of course function that create the chart onto your div element with an id of container

    function plotChartData(dataseries, xtitle)
{
    myChart = new Highcharts.Chart({
        chart: {
            renderTo: 'container',
            type: 'line',
            zoomType: 'xy',
            panning: true,
            panKey: 'shift',
            plotBorderWidth: 1
        },
        credits: {
            enabled: false
        },
        title: {
            text: 'My Sample Chart'
        },
        legend: {
            layout: 'horizontal',
            align: 'left',
            itemDistance: 10,
            borderWidth: 0,
            itemMarginTop: 0,
            itemMarginBottom: 0,
            padding: 20
        },
        plotOptions: {
            series: {
                states: {
                    hover: {
                        enabled: false
                    }
                },
                dataLabels: {
                    enabled: false,
                    format: '{y}'
                },
                allowPointSelect: false
            }
        },
        xAxis: {
            type: 'datetime',
            labels: {
                rotation: -60,
                format: '{value:%d %b %Y %I:%M}',
                style: {
                    fontSize: '9px',
                    fontFamily: 'Verdana, sans-serif'
                }
            },
            crosshair: {                  
                enabled: true
            }
        },
        yAxis: {
            gridLineColor: '#DDDDDD',
            gridLineWidth: 0.5
        },
        tooltip: {
            positioner: function () {
                return {
                    x: this.chart.plotLeft,
                    y: this.chart.plotTop
                }
            },
            useHTML: true,
            pointFormat: '<small><font color="{series.color}"><strong>{series.name}</strong></font>: <strong>{point.y}</strong></small><br/>',
            headerFormat: '<span style="font-size: 8px">{point.key}</span><br/>',
            xDateFormat: '%d-%m-%Y %H:%M:%S',
            shared: true,
            valueDecimals: 2,
            followPointer: true,
            shadow: false,
            borderWidth: 0,
            backgroundColor: 'rgba(255,255,255,0.8)'
        },
        series: [{
            name: xtitle,
            data: dataseries
        }]
    });
}

The above script and configuration displays the data into my highchart. Isn't that amazing!