Avatar of B O
B O asked on

How do I update the legend in amChart after loading new data in the chart

Hi there,


I am busy with amChart, a library used to create charts,

I have set a function which the user can use to make a query of a period.


The issue is how can I update the legend in amChart after loading new data.

I am not sure but I was trying to use function called:

deepInvalidate() (https://www.amcharts.com/docs/v4/reference/legend/)


Unfortunatley I didnt managed to reload the legend after making a ajax call.


code:

<div>
    <h2>amChart update</h2>
    <form action="" method="get" id="am_chart_query_selection">
        <label for="date_from">Search period:</label>
        <input type="date" id="date_from" name="date_from">

        <label for="date_untill"> t/m </label>
        <input type="date" id="date_untill" name="date_untill">

        <button id="submit" name="submit" value="search">search</button>
    </form>
    <div id="chartdiv"></div>
</div>

<script>

    am4core.ready(function() {

        am4core.useTheme(am4themes_animated);

// Create chart instance
        let chart = am4core.create("chartdiv", am4charts.XYChart);

// Add data
//         chart.data = [{
//             "2017": 450,
//             "2018": 362,
//             "2019": 410,
//             "date": 'Jan'
//         }, {
//             "2017": 455,
//             "2018": 365,
//             "2019": 415,
//             "date": 'Feb'
//         }, {
//             "2017": 450,
//             "2018": 362,
//             "2019": 425,
//             "date": 'Mrt'
//         }, {
//             "2017": 450,
//             "2018": 362,
//             "2019": 435,
//             "date": 'Apr'
//         }];

        chart.data = <?= $test_array_json ?>;



// Create axes
        let dateAxis = chart.xAxes.push(new am4charts.CategoryAxis());
        dateAxis.renderer.grid.template.location = 0;
        dateAxis.dataFields.category = "date";

        let valueAxis = chart.yAxes.push(new am4charts.ValueAxis());

        chart.scrollbarX = new am4core.Scrollbar();

// Create series
        function createSeries(field, name) {

            let series = chart.series.push(new am4charts.LineSeries());
            series.dataFields.valueY = field;

            series.dataFields.categoryX = "date";
            series.name = name;
            // series.tooltipText.disabled = true;
            series.strokeWidth = 2;

            let bullet = series.bullets.push(new am4charts.CircleBullet());
            bullet.circle.stroke = am4core.color("#fff");
            bullet.circle.strokeWidth = 2;

            return series;
        }
        console.log("chart.length[0]",Object.keys(chart.data[0]));

        let count_serie = Object.keys(chart.data[0]);

        count_serie.pop();

        console.log("count_serie",count_serie);

        for(let i = 0; i < count_serie.length; i++ ) {
            let serie_val = "value" + i;
            let serie_name = count_serie[i];

            // console.log("length serie prop", count_serie.length);
            // console.log("Series#", serie_name);
            // console.log("Series#", serie_val);

            let serie = createSeries(serie_name, serie_name);
        }

        chart.legend = new am4charts.Legend();
        chart.cursor = new am4charts.XYCursor();

    // });

        $("#am_chart_query_selection").on('submit', function(e){
            e.preventDefault();
//
            let date_from = new Date($('#date_from').val());
            let day_from = date_from.getDate() < 9 ? '0' + (date_from.getDate()) : date_from.getDate();
            // let day_from = date_from.getDate();
            let month_from = date_from.getMonth() < 9 ? '0' + (date_from.getMonth() + 1) : date_from.getMonth() + 1 ;
            // let month_from = date_from.getMonth() + 1;
            let year_from = date_from.getFullYear();

            //get date until
            let date_untill = new Date($('#date_untill').val());
            let day_untill = date_untill.getDate() < 9 ? '0' + (date_untill.getDate()) : date_untill.getDate();
            // let day_untill = date_untill.getDate();
            let month_untill = date_untill.getMonth() + 1 < 9 ? '0' + (date_untill.getMonth() + 1) : date_untill.getMonth() + 1 ;
            // let month_untill = date_untill.getMonth() + 1;
            let year_untill = date_untill.getFullYear();
            // let from = [day_from, month_from, year_from].join('/');
            // let format_start_date = [year_from, month_from, day_from].join('');
            let format_start_date = [year_from, month_from, day_from].join('');
            let start_date = String(format_start_date);
            // let untill = [day_untill, month_untill, year_untill].join('/');
            // let format_end_date = [year_untill, month_untill, day_untill].join('');
            let format_end_date = [year_untill, month_untill, day_untill].join('');
            let end_date = String(format_end_date);
            let items = {start: start_date, end: end_date};

            // function getArrayMax(array){
            //     return Math.max.apply(null, array);
            // }
            // function getArrayMin(array){
            //     return Math.min.apply(null, array);
            // }

           let new_amChart_data = '';
//
            console.log(items);
            $.ajax({
                url: '/xxxxxxxxxxx', //?start='+start_date+'&end='+end_date,
                method: "GET",
                data: items,
                dataType: "JSON",
                success: function(response){
                    console.log("stringify", JSON.stringify(response));
                    console.log("regular", response);
                    // collect dates

                    chart.data = response;
                    // chart.validateData();

                    function createSeries(field, name) {

                        let series = chart.series.push(new am4charts.LineSeries());
                        series.dataFields.valueY = field;

                        series.dataFields.categoryX = "date";
                        series.name = name;
                        // series.tooltipText.disabled = true;
                        series.strokeWidth = 2;

                        let bullet = series.bullets.push(new am4charts.CircleBullet());
                        bullet.circle.stroke = am4core.color("#fff");
                        bullet.circle.strokeWidth = 2;

                        return series;
                    }

                    let count_serie = Object.keys(chart.data[0]);

                    count_serie.pop();

                    console.log("count_serie",count_serie);

                    for(let i = 0; i < count_serie.length; i++ ) {
                        let serie_val = "value" + i;
                        let serie_name = count_serie[i];

                        // console.log("length serie prop", count_serie.length);
                        // console.log("Series#", serie_name);
                        // console.log("Series#", serie_val);

                        let serie = createSeries(serie_name, serie_name);
                    }
                    chart.legend = new am4charts.Legend();

                    chart.legend.deepInvalidate();

                },
                error: function (e) {
                    alert('Something went wrong with uploading the data');
                    console.log("Unsuccessful:", e);
                }
            });

            // chart.data = new_amChart_data;
        });
//
    }); // end am4core.ready()

</script>

Open in new window


AJAXJSONJavaScript

Avatar of undefined
Last Comment
B O

8/22/2022 - Mon
Scott Fell

I don't use this library. From what I can see though, you have starting on your line 51 above

// Create axes
        let dateAxis = chart.xAxes.push(new am4charts.CategoryAxis());
        dateAxis.renderer.grid.template.location = 0;
        dateAxis.dataFields.category = "date";

Open in new window

You are not setting your dataAxis in your success function

When trouble shooting, I find it is best to clear unnecessary code.  You have a lot of code you commented out. If you are worried about remembering what you did, just save the file as is to something new like file.php.bak.  Then remove all the code that you commented out.  

  // function getArrayMax(array){
            //     return Math.max.apply(null, array);
            // }
            // function getArrayMin(array){
            //     return Math.min.apply(null, array);
            // }

Open in new window

Leave your comments like // Create series  that help remind what you are doing.  Cleaning up like this will help make your code easier to read.
ASKER CERTIFIED SOLUTION
B O

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Your help has saved me hundreds of hours of internet surfing.
fblack61