troubleshooting Question

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

Avatar of B O
B O asked on
DatabasesAJAXHTML
3 Comments1 Solution22 ViewsLast Modified:

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


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




ASKER CERTIFIED SOLUTION
David H.H.Lee
Digital Marketing (Hospitality)
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 3 Comments.
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 3 Comments.
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