Anagio
Anagio

Reputation: 3075

Highcharts check if a series is empty

I have this code in an AJAX success event, this AJAX fires after a date range is changed and updated, if there's no data to return I return a json array where empty == true.

If before the AJAX event fired there was data in the chart the nested if condition would fire and remove each data series.

The problem is if the chart initially loads with no data, then the user changes dates, the AJAX fires, see's no data the if condition is still firing and I get the error Uncaught TypeError: Cannot read property 'series' of undefined

Am I not checking if the chart series has data correctly? Isn't the if condition saying if the series length is greater than 0 run the while loop? How can I skip the while loop when there is no data in the series?

var chart = $('#chart').highcharts();
if (data.empty == 'true') {
    alert('empty');

    $('#chart').html( "<div class='empty-chart'>No data available for selected date range</div>" );

    if (chart.series.length > 0) {
        while (chart.series.length > 0) {
            chart.series[0].remove(true);
        }
    }
}

Upvotes: 0

Views: 9779

Answers (2)

epoch
epoch

Reputation: 16615

if (chart.series.length > 0) {
----^^^^^--------------------

chart is undefined, where are you storing it? Make sure it refers to your Highcharts Chart; alternatively, if you know it to be undefined in certain cases, just check for "truthy-ness" as well.

    if (chart && chart.series && chart.series.length > 0) {

UPDATE

HighSoft has a custom module for this!

Upvotes: 2

Paweł Fus
Paweł Fus

Reputation: 45079

Change order in your function, and use destroy() instead of removing series one-by-one:

var chart = $('#chart').highcharts();
if (data.empty == 'true') {
    alert('empty');

    chart.destroy(); //why remove all series, while you can remove chart to free some space and resources

    $('#chart').html( "<div class='empty-chart'>No data available for selected date range</div>" ); //now show some information about chart
}

Otherwise you are first adding custom text to chart container, removing all SVG elements. Then when you call remove() or destory() and Highcharts tries to remove SVG elements which doesn't exist.. and that produces error.

Upvotes: 1

Related Questions