Goro Goro - 19 days ago 10
JSON Question

Showing data from database in AmCharts

I'm trying to make graph using AmCharts and following this example on their site: https://www.amcharts.com/kbase/using-data-loader-to-connect-charts-to-mysql-data-base/

My original code is

var chart = AmCharts.makeChart("chart_1", {
"pathToImages": App.getGlobalPluginsPath() + "amcharts/amcharts/images/",

"dataProvider": [{
"year": 2009,
"income": 23.5,
"expenses": 18.1
}, {
"year": 2010,
"income": 26.2,
"expenses": 22.8
}],
// bunch of graph stylings
});

$('#chart_1').closest('.portlet').find('.fullscreen').click(function() {
chart.invalidateSize();
});
}


My attempt to load data from mysql

var chart = AmCharts.makeChart("chart_1", {
"type": "serial",
"dataProvider": {
"url": "data.php"
},
"pathToImages": App.getGlobalPluginsPath() + "amcharts/amcharts/images/",

// bunch on graphs style

});

$('#chart_1').closest('.portlet').find('.fullscreen').click(function() {
chart.invalidateSize();
});
}


The original code with data which is hardcoded is working. The below with mysql doesn't work. It's blank page and doesn't show the graph. Also no errors on console.

data.php
is working also and return json array.

Can anyone help here?

In case php part is needed also

$query = "
SELECT *
FROM my_chart_data
ORDER BY category ASC";
$result = $link->query( $query );

// All good?
if ( !$result ) {
// Nope
$message = 'Invalid query: ' . $link->error . "n";
$message .= 'Whole query: ' . $query;
die( $message );
}


// Set proper HTTP response headers
header( 'Content-Type: application/json' );

// Print out rows
$data = array();
while ( $row = $result->fetch_assoc() ) {
$data[] = $row;
}
echo json_encode( $data );

Answer

The dataProvider doesn't take a url - you need to change it to dataLoader if you're using the dataLoader plugin. To use the dataLoader plugin, you first need to include the plugin along with the other chart libraries like so:

<!-- chart libraries -->
<script type="text/javascript" src="//www.amcharts.com/lib/3/amcharts.js"></script>
<script type="text/javascript" src="//www.amcharts.com/lib/3/serial.js"></script>
<!-- include dataloader -->
<script type="text/javascript" src="//www.amcharts.com/lib/3/plugins/dataloader/dataloader.min.js"></script>

Then change dataProvider to dataLoader. dataLoader takes a url:

var chart = AmCharts.makeChart("chart_1", {
    "type": "serial",
    "dataLoader": {
        "url": "data.php"
    },
    // ...
});

Full dataloader documentation can be found on the github page here.

Comments