Avatar of B O
B O

asked on 

I am trying to dynamically get data into the highChart using input from the user, I got the data only its not being previewed in the chart

I am creating a chart (highChart) that loads data dynamically from the database.

I got a form with two date input that the user can use to insert a period e.g. 1 Jan 2019 - 1 jan 2021.


The Data wil be called using ajax.


The input part and getting the data works.

But when trying to preview the data in the chart, 

I got a issue:

- when I console.log the data from ajax it seems to be the correct format,

  but it doens preview a line in the chart


success :  [{"name":"2019","data":[4786961,4786961,4786961,4786961,4786961,4786961,4786961,4786961,4786961,4786961,4786961,4786961]},{"name":"2020","data":[4786961,4786961,4786961,4786961,4786961,4786961,4786961,4786961,4786961,4786961,4786961,4786961]}]

Open in new window

User generated image


code: HTML & SCRIPT

<div>
    <h3>highChart with ajax</h3>
    <br>
    <div id="test"></div>
    <br>
    <form action="" method="post" 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="raw"></div>
    <br>
    <script>

        let submit = document.getElementById("submit");
        let newLine = "\r\n";

        // const addEventItemObject = (title, description, startDate, endDate, event) => {
        //     event.preventDefault();
        // };

        $("#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() + 1) : 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() + 1) : 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};

            console.log(items);
            $.ajax({
                url: '/xx/xxxxx/xxxx/highChart.ajax.php',
                method: "POST",
                data: items,
                dataType: "text",
                success: function(response){
                    console.log("success : ", response);
                    alert(response);
                    // $("#test").html(response).fadeIn();

                    Highcharts.chart('raw', {

                        title: {
                            text: 'Periodieke grafiek'
                        },

                        subtitle: {
                            text: 'Kleisteen'
                        },

                        yAxis: {
                            title: {
                                text: 'Amount'
                            }
                        },

                        xAxis: {
                            accessibility: {
                                rangeDescription: 'Date'
                            }
                        },

                        legend: {
                            layout: 'vertical',
                            align: 'right',
                            verticalAlign: 'middle'
                        },

                        plotOptions: {
                            series: {
                                label: {
                                    connectorAllowed: false
                                },
                                pointStart: 1
                            }
                        },

                        series: [response],
                       // series: response,                        responsive: {
                            rules: [{
                                condition: {
                                    maxWidth: 500
                                },
                                chartOptions: {
                                    legend: {
                                        layout: 'horizontal',
                                        align: 'center',
                                        verticalAlign: 'bottom'
                                    }
                                }
                            }]
                        }

                    });
                },

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

Open in new window


code: php (ajax call response)


//get Data
$_sel = "
     SELECT  - SUM(tbl.valuta) as tot_amount
    FROM    tbl
    WHERE   tbl.id = '$relation_id' AND
            tbl.date BETWEEN '{$period['start']}' AND '{$period['end']}' AND
            tbl.type_id IN (80,81,82)
    GROUP BY tbl.id, tbl.month
    ;";

    // returns only value (higher speed then row)
    $res_tot_amount = $oDbConn->selectValue($_sel, 'noshow');
    $res_num_rows = $oDbConn->getNumRows();

    // if there is data then set amount, else amount=0
    if ($res_num_rows > 0) {

        $temp_amount = $res_tot_amount;
    }
    else {

        $temp_amount = '0';
    }

    // build new base array for single line serie in charts
    $chart_base_data[$key] = [
        'year'=>$value['year'],
        'period'=>$value['year_month'],
        'period_view'=>$value['month_year_name'],
        'amount'=>$temp_amount,
    ];

    // or gather for stacked series
    $chart_base_data_stacked[$value['year']][$key] = [
        'year'=>$value['year'],
        'period'=>$value['year_month'],
        'month_short'=>$value['month_short'],
        'period_view'=>$value['month_year_name'],
        'amount'=>$temp_amount,
    ];

    // get month short names for y-axis
    $months_short[$value['month_short']] = '';
endforeach;

/**     create vars for single and multi series highChart   **/
// set years in var
$year_arr = array();
$year_data_arr = array();

/**     Load multi series in Chart      **/

$set_chart = array();

foreach($chart_base_data_stacked as $key_single_data_stack => $value_data_stack):
    //prevent duplicating years in array
    if(!in_array($key_single_data_stack, $year_arr)):
        //put all years in arr
        $year_arr[] = $key_single_data_stack;
    endif;
endforeach;
//check each year in array
foreach($year_arr as $year_key => $year_val):
//    print_r($year_val. "<br>");
//    echo "<hr>";
    $check_amount = array();
    // foreach obj set key and value
    foreach($chart_base_data_stacked as $key => $val):
        // check if key/ year and from obj year matches
        if(in_array($key, array($year_val))):
//            print_r($val[0] . " end<br>" . "<hr>");
            foreach($val as $amount):
                // set in arr the amount of obj
//                $check_amount[] = round((float) $amount["amount"], 2);
                $check_amount[] = (int) $amount["amount"];
    //            print_r($chart_data. " end<br>" . "<hr>");
            endforeach;
            $chart_data[] = $check_amount;
        endif;
    endforeach;
endforeach;


$data_set_chart = array_combine($year_arr, $chart_data);

foreach($data_set_chart as $key => $val):
    $set_chart[] = [
        'name' => strval($key),
        'data' => $val
    ];
endforeach;

////prepare multi serie data for chart
sendJSON($set_chart);

Open in new window




DatabasesAJAXHTML

Avatar of undefined
Last Comment
David H.H.Lee
Avatar of David H.H.Lee
David H.H.Lee
Flag of Malaysia image

The input part and getting the data works.But when trying to preview the data in the chart, 
You may use chart's update function to update the series option:
Highcharts.update({series: response});

Open in new window

Avatar of B O
B O

ASKER

Thank you for answering Sir,

I first looked for examples online and tried it but I think I might be doing something wrong.

Could be kind to look at my code:
<script>

   const chart =  Highcharts.chart('raw', {

        title: {
            text: 'Periodieke grafiek'
        },

        subtitle: {
            text: 'Kleisteen'
        },

        yAxis: {
            title: {
                text: 'Amount'
            }
        },

        xAxis: {
            accessibility: {
                rangeDescription: 'Date'
            }
        },

        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'middle'
        },

        plotOptions: {
            series: {
                label: {
                    connectorAllowed: false
                },
                pointStart: 1
            }
        },

        responsive: {
            rules: [{
                condition: {
                    maxWidth: 500
                },
                chartOptions: {
                    legend: {
                        layout: 'horizontal',
                        align: 'center',
                        verticalAlign: 'bottom'
                    }
                }
            }]
        }

    });

    let submit = document.getElementById("submit");
    let newLine = "\r\n";

    // const addEventItemObject = (title, description, startDate, endDate, event) => {
    //     event.preventDefault();
    // };

    $("#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() + 1) : 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() + 1) : 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};

        console.log(items);
        $.ajax({
            url: '/xx/xxxxx/xxx/highChart.ajax.php',
            method: "POST",
            data: items,
            dataType: "text",
            success: function(response){
                console.log("success : ", response);
                alert(response);
                // $("#test").html(response).fadeIn();

                chart.update({series: response});
            },

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

Open in new window


User generated image
ASKER CERTIFIED SOLUTION
Avatar of David H.H.Lee
David H.H.Lee
Flag of Malaysia image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
HTML
HTML

HTML (HyperText Markup Language) is the main markup language for creating web pages and other information to be displayed in a web browser, providing both the structure and content for what is sent from a web server through the use of tags. The current implementation of the HTML specification is HTML5.

62K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo