troubleshooting Question

How can the amChart be updated with ajax

Avatar of B O
B O asked on
AJAXHTMLJSONJavaScript
1 Comment1 Solution9 ViewsLast Modified:

What I am trying to do is upload data to amChart with user input,

The user inserts the dates (start to end)
I am using ajax to retrieve the data,

The ajax file collects the data correctly,

Trying to load new data to the chart and clearing the previous data is where I am getting stuck.


html:

<div>
    <h2>amChart update</h2>
    <form action="" method="get" id="period_selection_high_chart">
        <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>

Open in new window


script:

am4core.ready(function() {

// Themes begin
        am4core.useTheme(am4themes_animated);
// Themes end

        const chart = am4core.create("chartdiv", am4charts.XYChart);
        chart.paddingRight = 20;
        // Load data from mySQL
        let myChartData = <?= $chart_data_json; ?>;
        console.log("amChart",myChartData);

        chart.data = myChartData;

        let dateAxis = chart.xAxes.push(new am4charts.DateAxis());
        dateAxis.renderer.grid.template.location = 0;
        dateAxis.minZoomCount = 5;

        // chart.dateFormatter.dateFormat = "yyyy-MM-dd";
// this makes the data to be grouped
        dateAxis.groupData = true;
        dateAxis.groupCount = 500;

        // dateAxis.dateFormats.setKey("day", { "year": "numeric", "month": "short", "day": "numeric" });

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

        let series = chart.series.push(new am4charts.LineSeries());
        series.dataFields.dateX = "date";
        series.dataFields.valueY = "value";
        series.tooltipText = "{valueY}";
        series.tooltip.pointerOrientation = "vertical";
        series.tooltip.background.fillOpacity = 0.5;

        chart.cursor = new am4charts.XYCursor();
        chart.cursor.xAxis = dateAxis;

        let scrollbarX = new am4core.Scrollbar();
        scrollbarX.marginBottom = 20;
        chart.scrollbarX = scrollbarX;
    }); // end am4core.ready()

        $("#period_selection_high_chart").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 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 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);
            }

            console.log(items);
            $.ajax({
                url: '/bo/dev_teddy/ajax/amChart.ajax.php', //?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

                    // let chartData = reloadData();


                    // chart.validateData();
                    // chart.validateData();

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

Open in new window



ajax file:

<?php

// select multiple rows
$_sel = "
SELECT  - SUM(tbl.units) as amount,
calc_year_month,
YEAR(calc_date) as year,
MONTH(calc_date) as month,
DAY(calc_date) as day,
calc_date

FROM tbl_journal
WHERE tbl.id = '$relation_id' AND

calc_year_month BETWEEN '201901' AND '202112' AND
ledger_type_id IN (80,81,82)
GROUP BY month
ORDER  BY month
;";

$sales_per_month = $dbConn->selectAll($_sel);

$chartData = [];

function sendJSON($data, $terminate = true) {
//    header('Content-type: application/json');
    echo json_encode($data);
    if ($terminate) die();
}

foreach ($sales_per_month as $key){
$chartData[] = (object)[
'date' => substr($key["calc_date"], 0, 10),
'value' => $key["amount"],
];
}

$chart_data_json = json_encode($chartData);
//print_array($chartData, '$chartData');

//$q_res_num_rows = $oDbConn->getNumRows();
//
//$q_res_sales_per_month_json = json_encode($q_res_sales_per_month);

//var_dump($chartData);

echo $chart_data_json;

Open in new window


view ajax:

[{"date":"2019-01-01","value":"1234560.75.99"},{"date":"2019-02-25","value":"1234561.75"},{"date":"2019-03-15","value":"1234563.75"},{"date":"2019-04-15","value":"1234565.75"},{"date":"2019-05-15","value":"1234567.75"},{"date":"2019-06-15","value":"1234569.75"},{"date":"2019-07-30","value":"1234572.75"}]

Open in new window

ASKER CERTIFIED SOLUTION
B O

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Log in to continue reading
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform for $9.99/mo
View membership options
Unlock 1 Answer and 1 Comment.
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
The Value of Experts Exchange in My Daily IT Life

Experts Exchange (EE) has become my company's go-to resource to get answers. I've used EE to make decisions, solve problems and even save customers. OutagesIO has been a challenging project and... Keep reading >>

Mike

Owner of Outages.IO
Phoenix, Arizona, United States
Member Since 2016
Join a full scale community that combines the best parts of other tools into one platform.
Unlock 1 Answer and 1 Comment.
View membership options
“All of life is about relationships, and EE has made a virtual community a real community. It lifts everyone's boat.”
William Peck

Member since 2004