I'm using dataLoader for retrieving data in AmChart from PHP/MySql backend.
However the simple serial bar chart is generated but don't know what is the problem with rendering graphs, graphs are not getting generated.
Then with another try using ajax call I've done re-parsing of JSON response to object via loop just like generateChartData(), it's the same data. But still chart is not getting rendered.
These options I've passed to dataLoader
"dataLoader": {
"url": 'data.php',
"format": "json"
}
In ajax call I call chart.validateData() but this is not working. What can done to solve this?
setting async option for ajax request false gives warning and doesn't work too.
Here is the js code app.js:
var chartData = [];
loadChartData();
function loadChartData() {
var time = new Date();
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var cur = new Date();
var data = JSON.parse(ajax.responseText);
data.forEach(function(d, i) {
chartData.push({
date: d.date,
visits: parseInt(d.visits, 10)
});
});
// alert('Request Completed in '+ (cur - time)+ ' mili seconds');
console.log(chartData.length);
// chart.validateData();
}
};
ajax.open('GET', 'data.php', true);
ajax.setRequestHeader("Content-type", "application/json");
ajax.send();
}
var chart = AmCharts.makeChart("chartdiv", {
"type": "serial",
"theme": "light",
"marginRight": 80,
// "dataLoader": {
// "url": "data.php",
// "format": "json"
// }, this doesn't work too!
"dataProvider": chartData,
"dataDateFormat": "YYYY-MM-DD",
"valueAxes": [{
"position": "left",
"title": "Energy Generated"
}],
"graphs": [{
"id": "g1",
"fillAlphas": 0.4,
"valueField": "visits",
"balloonText": "<div style='margin:5px; font-size:19px;'><b>[[value]]kWh</b></div>"
}],
"chartScrollbar": {
"graph": "g1",
"scrollbarHeight": 80,
"backgroundAlpha": 0,
"selectedBackgroundAlpha": 0.1,
"selectedBackgroundColor": "#888888",
"graphFillAlpha": 0,
"graphLineAlpha": 0.5,
"selectedGraphFillAlpha": 0,
"selectedGraphLineAlpha": 1,
"autoGridCount": true,
"color": "#AAAAAA"
},
"chartCursor": {
"categoryBalloonDateFormat": "JJ:NN, DD MMMM",
"cursorPosition": "mouse"
},
"categoryField": "date",
"categoryAxis": {
"minPeriod": "mm",
"parseDates": true
},
});
// this method is called when chart is first inited as we listen for "dataUpdated" event
function zoomChart() {
// different zoom methods can be used - zoomToIndexes, zoomToDates, zoomToCategoryValues
chart.zoomToIndexes( chart.dataProvider.length - 250, chart.dataProvider.length - 100);
}
zoomChart();
And here is my php code data.php
$link = new mysqli( "localhost", "root", "", "test" );
if ( $link->connect_errno ) {
die ("Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error);
}
// Fetch the data
$query = "SELECT *
FROM daily_visits
ORDER BY date ASC";
$result = $link->query( $query );
// All good?
if ( !$result ) {
// Nope
$message = 'Invalid query: ' . $link->error . "\n";
$message .= 'Whole query: ' . $query;
die( $message );
}
$data = array();
while ( $row = $result->fetch_assoc() ) {
$data[] = $row;
}
echo json_encode( $data );
// Close the connection
mysqli_close($link);
And the returned json looks like
[{"date":"2016-09-03","visits":"16"},{"date":"2016-09-03","visits":"49"},...]
Remove "dataProvider": chartData from makeChart, when using dataloader.
You should update the instance of the chart:
let chartInstance = AmChart.makeCharts(...);
(<any>this.chartInstance).dataProvider = parsedArray; // yes, here we update the dataProvider directly
If anyone doesn't understand this, please leave a message here.
Related
So this is the first time i have really worked with high charts i have some data reading into high charts from my MySQL database, but the next step is to try and set up a high stocks chart. Whenever i try and use the same method as i did with high charts the chart doesn't work? This is what i want to aim for - StockChartDemo
PHP Code:
$conn = new mysqli($servername, $username, $password, $dbName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "(SELECT date AS time ,IFNULL(RH,'null')AS humidity
FROM test ORDER BY date DESC LIMIT 20) ORDER BY time ASC";
$result = $conn->query($sql);
if ($result->num_rows>0){
$count =0;
echo '[';
while($row=$result->fetch_assoc()){
echo '['.$row["time"].',' .$row["humidity"].']';
$count++;
if ($count<"20"){
echo ',';
}
}
echo ']';
}else{
echo "[[],[]]";
}
$conn->close();
?>
html & jQuery:
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="highstock.js"></script>
</head>
<script type="text/javascript">
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var options = {
chart: {
renderTo: 'tempcontainer',
alignTicks: false,
height:320,
},
rangeSelector: {
selected: 1
},
title: {
text: 'Relative humidity'
},
series: [{
type: 'column',
name: 'Humidity',
data: json,
dataGrouping: {
units: [[
'month', // unit name
[1] // allowed multiples
], [
'week',
[1, 2, 3, 4, 6]
]]
}
}]
}
$.getJSON("stockdata.php", function(json) { /*Get the array data in data.php using jquery getJSON function*/
options.series[0].data = json; /*assign the array variable to chart data object*/
chart = new Highcharts.stockChart(options); /*create a new chart*/
});
function refreshChart(){ /*function is called every set interval to refresh(recreate the chart) with the new data from data.php*/
setInterval(function(){
$.getJSON("stockdata.php", function(json) {
options.series[0].data = json;
chart = new Highcharts.stockChart(options);
});
},60000);
}
});
</script>
<div id="tempcontainer"></div>
Presuming your query is returning the correct data you want. (I'm not up for mocking it out to test your query)
You should switch out the following code, and all that in-between.
if ($result->num_rows>0){
//snip
}
To use json_encode() instead.
$series = [];
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$series[] = [
$row["time"],
$row["humidity"]
];
}
}
header('Content-Type: application/json');
exit(json_encode($series));
[
{ "category": "Q12012", "value1": 31845935.15, "value3": 0.00 },
{ "category": "Q22012", "value1": 29674500.79, "value3": 0.00 },
{ "category": "Q32012", "value1": 30935441.96, "value3": 0.00 },
{ "category": "Q42012", "value1": 31748214.07, "value3": 0.00 },
{ "category": "Q12013", "value1": 36601910.60, "value3": 31051022.99 },
{ "category": "Q22013", "value1": 39663505.35, "value3": 32240016.86 },
{ "category": "Q32013", "value1": 39822373.03, "value3": 34737268.00 },
{ "category": "Q42013", "value1": 37821101.06, "value3": 36959000.76 },
{ "category": "Q12014", "value1": 47430411.67, "value3": 38477222.51 },
{ "category": "Q22014", "value1": 47493801.18, "value3": 41184347.78 },
{ "category": "Q32014", "value1": 0.00, "value3": 43141921.74 }
]
Picture showing my graph was created using the code below.
How can I not display if my data value = 0?
Means that if my data == 0.00, I don't want it to be plotted on the graph. Where can I set them?
How can I name both line (orange and yellow line), my x-axis and y-axis?
thank you
<!-- the chart code -->
<script>
var chart;
// create chart
AmCharts.ready(function() {
// load the data
var chartData = AmCharts.loadJSON('dataMainForecasting.php');
// SERIAL CHART
chart = new AmCharts.AmSerialChart();
chart.pathToImages = "http://www.amcharts.com/lib/images/";
chart.dataProvider = chartData;
chart.categoryField = "category";
chart.title = 'Hello';
//chart.dataDateFormat = "YYYY-MM-DD";
// GRAPHS
var graph1 = new AmCharts.AmGraph();
graph1.valueField = "value1";
graph1.bullet = "round";
graph1.bulletBorderColor = "#FFFFFF";
graph1.bulletBorderThickness = 2;
graph1.lineThickness = 2;
graph1.lineAlpha = 0.5;
chart.addGraph(graph1);
var graph2 = new AmCharts.AmGraph();
graph2.valueField = "value2";
graph2.bullet = "round";
graph2.bulletBorderColor = "#FFFFFF";
graph2.bulletBorderThickness = 2;
graph2.lineThickness = 2;
graph2.lineAlpha = 0.5;
chart.addGraph(graph2);
// CATEGORY AXIS
chart.categoryAxis.parseString = true;
// WRITE
chart.write("Quarter2");
});
json = json.filter(function(val) {
return val !== 0;
});
</script>
and this is all my data being extracted from
mysql_select_db("test",$connect);
// Fetch the data
$query = "
SELECT *
FROM `table 5` ";
$result = mysql_query( $query );
// All good?
if ( !$result ) {
// Nope
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die( $message );
}
// Print out rows
// Print out rows
$prefix = '';
echo "[\n";
while ( $row = mysql_fetch_assoc( $result ) ) {
echo $prefix . " {\n";
echo ' "category": "' . $row['category'] . '",' . "\n";
echo ' "value1": ' . $row['value1'] . ',' . "\n";
echo ' "value2": ' . $row['value2'] . '' . "\n";
echo " }";
$prefix = ",\n";
}
echo "\n]";
// Close the connection
//mysql_close($link);
?>
Latest answer
check AmChart addLabel method
see this working Demo
I've added implementations for both 1) remove zero values from graph and 2) Change labels of axes.
JS
//function prototype
addLabel(x, y, text, align, size, color, rotation, alpha, bold, url)
where
x - horizontal coordinate
y - vertical coordinate
text - label's text
align - alignment (left/right/center)
size - text size
color - text color
rotation - angle of rotation
alpha - label alpha
bold - specifies if text is bold (true/false)
url - url of a
This was my answer earlier before the original question was changed
you can just pre-process the data you are feeding to the chart api and remove the ones with zero value. This would be easy instead of trying to modify the graph api.
check the JSFiddle Demo
HTML:
<script src="http://code.highcharts.com/highcharts.js"></script>
<div id="container" style="height: 400px"></div>
JS:
$(function() {
var options = {
chart: {
renderTo: 'container',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: ''
},
tooltip: {
formatter: function() {
return '<b>' + this.point.name + '</b>: ' + this.percentage + ' %';
}
},
plotOptions: {
line: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000'
}
}
},
events: {
load: function() {
var theChart = this;
var theSeries = this.series;
}
},
series: [{
type: 'line',
name: 'Browser share'
}]
};
//though this is a simple array, you will use a real json object here
json = [11, 71.5, 0, 0, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4];
json = json.filter(function(val) {
return val !== 0;
});
options.series[0].data = json;
$('#container').highcharts(options);
});
So basically you need to change your code to something like this:
$.getJSON("dataHome.php", function(json) {
//now you need to remove the zeros
json = json.filter(function(val) {
return val !== 0;
});
options.series[0].data = json;
chart = new Highcharts.Chart(options);
});
you can remove an element from a json object using its key see this Link
Relatively new to HighCharts, PHP and JS but continuing to learn. I have searched extensively on the web but have not found anything that works so far.
I have a listing website that displays information on a variety of hospitals. As part of this offering, I am looking to show salary information unique to each hospital (~4,800) in HighCharts, using the WP post ID as the identifier.
I have a static chart showing across all hospitals as a placeholder right now but would like make this dynamic based on the individual hospital in question. I tried to use an Ajax POST command to push the right data without any luck thus far.
Any help or guidance would be greatly appreciated!
Code below:
JS Chart Display (Contained in a Widget)
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<!--
updatepage();
//--></script>
*** Function does not work when included ***
//var post_id = parseInt( ( document.body.className.match( /(?:^|\s)postid-([0-9]+)(?:\s|$)/ ) || [ 0, 0 ] )[1] ); // - JS to get post ID
var post_id = "1"; //Temporary post_id
jQuery(function($){
$('.section').click(function () {
jQuery.ajax({
url: http://www.rndeer.com/data.php,
type: 'POST',
data: post_id,
success:function(data) {
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
});
***********************
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'column',
marginRight: 130,
marginBottom: 25
},
colors: ['#0000FF', '#0066FF', '#3396d1'],
title: {
text: '<?php echo get_the_title();?>',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Salary ($ per / hour)'
},
plotLines: [{
value: 0,
width: 1,
color: '#3396d1'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': $'+ this.y+' per / hour';
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: []
}
$.getJSON("data.php", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
options.series[1] = json[2];
options.series[2] = json[3];
chart = new Highcharts.Chart(options);
});
});
</script>
Data.PHP Script
<?php
$con = mysql_connect("localhost","Database_Name","Password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
//$post_id = $_POST['post_id']; - Attempt at getting posted data
$post_id = '1';
mysql_select_db("Database Name", $con);
$query = mysql_query("SELECT hospital, newgrad, median, high FROM salary_estimates WHERE id='".$post_id."'");
$category = array();
$category['name'] = 'Hospital';
$series1 = array();
$series1['name'] = 'New Grad';
$series2 = array();
$series2['name'] = 'Median';
$series3 = array();
$series3['name'] = 'High';
while($r = mysql_fetch_array($query)) {
$category['data'][] = $r['hospital'];
$series1['data'][] = $r['newgrad'];
$series2['data'][] = $r['median'];
$series3['data'][] = $r['high'];
}
$result = array();
array_push($result,$category);
array_push($result,$series1);
array_push($result,$series2);
array_push($result,$series3);
print json_encode($result, JSON_NUMERIC_CHECK);
mysql_close($con);
?>
I have used Jvectormap it is working well. Now its work function if I click country showing country name .
i have created simple database particular country. connected database via ajax its working well.its showing alert msg database created country.
created database Canada country.But now I want display database in when click Canada show details from database not in alert box? please help me?
script:
<script>
jQuery.noConflict();
jQuery(function(){
var $ = jQuery;
$('#focus-single').click(function(){
$('#map1').vectorMap('set', 'focus', {region: 'AU', animate: true});
});
$('#focus-multiple').click(function(){
$('#map1').vectorMap('set', 'focus', {regions: ['AU', 'JP'], animate: true});
});
$('#focus-coords').click(function(){
$('#map1').vectorMap('set', 'focus', {scale: 7, lat: 35, lng: 33, animate: true});
});
$('#focus-init').click(function(){
$('#map1').vectorMap('set', 'focus', {scale: 1, x: 0.5, y: 0.5, animate: true});
});
$('#map1').vectorMap({
map: 'world_mill_en',
panOnDrag: true,
focusOn: {
x: 0.5,
y: 0.5,
scale: 1,
animate: true
},
series: {
regions: [{
scale: ['#688FA0'],
normalizeFunction: 'polynomial',
values: {
// "TD":23.4,
// "TH": 312.61,
"TL": 0.62,
// "TZ":1.56,
"TO": 0.3,
// "TT": 21.2,
//"TM":21.2,
// "TR": 729.05,
//"TJ":21.2,
// "TN":4.3,
// "YE":0.3,
// "UA": 136.56,
// "QA":0.72,
"GB": 2258.57,
// "GA":4.6,
"US": 14624.18,
//"UG":4.3,
//"UY": 40.71,
// "UZ":0.72,
"VU": 0.72,
// "VE":5.77,
// "VN": 101.99,
// "ZW":8.4,
// "ZM":2.5,
}
}]
},
onRegionClick: function (event, code) {
var map = $('#map1').vectorMap('get', 'mapObject');
var name = map.getRegionName(code);
/*
onRegionLabelShow: function(e, el, code) {
//search through data to find the selected country by it's code
var country = $.grep(data.countries, function(obj, index) {
return obj.code == code;
})[0]; //snag the first one
if (country != undefined) {
el.html(el.html() + "<br/><b>Code: </b>" +country.code + "<br/><b>Continent : </b> " + country.continent);
}
*/
// get from DB using ajax
$(document ).ready(function() {
$.ajax({
type: "GET",
url: 'database.php',
data: {country: name},
dataType: "text",
success: function(data){
// alert(data);
}
});
});
},
});
})
</script>
My PHP code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydatabase";
$_country = $_GET['country'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT countryId,country,pdogcoregion,ccl,category FROM countrydetails WHERE country='".$_country."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "country: " . $row["country"];
}
} else {
echo "No database";
}
$conn->close();
?>
name display from this file i update simple part code this file
$.fn.vectorMap('addMap', 'world_mill_en',{"insets": [{"width": 900.0, "top": 0, "height": 440.7063107441331, "bbox": [{"y": -12651089.408837218, "x": -19971805.562327016}, {"y": 6919135.471157653, "x": 19994044.625421535}], "left": 0}], "paths": {"BD": {"path": "M652.71,228.85l-0.04,1.38l-0.46,-0.21l-0.42,0.3l0.05,0.65l-0.17,-1.37l-0.48,-1.26l-1.08,-1.6l-0.23,-0.13l-2.31,-0.11l-0.31,0.36l0.21,0.98l-0.6,1.11l-0.8,-0.4l-0.37,0.09l-0.23,0.3l-0.54,-0.21l-0.78,-0.19l-0.38,-2.04l-0.83,-1.89l0.4,-1.5l-0.16,-0.35l-1.24,-0.57l0.36,-0.62l1.5,-0.95l0.02,-0.49l-1.62,-1.26l0.64,-1.31l1.7,1.0l0.12,0.04l0.96,0.11l0.19,1.62l0.25,0.26l2.38,0.37l2.32,-0.04l1.06,0.33l-0.92,1.79l-0.97,0.13l-0.23,0.16l-0.77,1.51l0.05,0.35l1.37,1.37l0.5,-0.14l0.35,-1.46l0.24,-0.0l1.24,3.92Z", "name": "Bangladesh"}, "BE": {"path": "M429.28,143.95l1.76,0.25l0.13,-0.01l2.16,-0.64l1.46,1.34l1.26,0.71l-0.23,1.8l-0.44,0.08l-0.24,0.25l-0.2,1.36l-1.8,-1.22l-0.23,-0.05l-1.14,0.23l-1.62,-1.43l-1.15,-1.31l-0.21,-0.1l-0.95,-0.04l-0.21,-0.68l1.66,-0.54Z", "name": "Belgium"}
Please help me anybody. I am new in jQuery and JavaScript.
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "country: " . $row["country"];
}
}
You are still returning the country.
try
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "category: " . $row["category"];
}
}
Now I am currently using Jvector Map. Its working well. When I click the country name its shows country name for default. Now I want to customize the label and show label database value?
Script code:
<script>
jQuery.noConflict();
jQuery(function(){
var $ = jQuery;
$('#focus-single').click(function(){
$('#map1').vectorMap('set', 'focus', {region: 'AU', animate: true});
});
$('#focus-multiple').click(function(){
$('#map1').vectorMap('set', 'focus', {regions: ['AU', 'JP'], animate: true});
});
$('#focus-coords').click(function(){
$('#map1').vectorMap('set', 'focus', {scale: 7, lat: 35, lng: 33, animate: true});
});
$('#focus-init').click(function(){
$('#map1').vectorMap('set', 'focus', {scale: 1, x: 0.5, y: 0.5, animate: true});
});
$('#map1').vectorMap({
map: 'world_mill_en',
panOnDrag: true,
focusOn: {
x: 0.5,
y: 0.5,
scale: 1,
animate: true
},
series: {
regions: [{
scale: ['#688FA0'],
normalizeFunction: 'polynomial',
values: {
// "YE":0.3,
// "UA": 136.56,
// "QA":0.72,
"GB": 2258.57,
// "GA":4.6,
"US": 14624.18,
//"UG":4.3,
//"UY": 40.71,
// "UZ":0.72,
"VU": 0.72,
// "VE":5.77,
// "VN": 101.99,
// "ZW":8.4,
// "ZM":2.5,
}
}]
},
onRegionClick: function (event, code) {
var map = $('#map1').vectorMap('get', 'mapObject');
var name = map.getRegionName(code);
$(document ).ready(function() {
$.ajax({
type: "GET",
url: 'database.php',
data: {country: name},
dataType: "text",
success: function(data){
alert(data);
}
});
});
},
});
})
</script>
Its MY script code when i click country showing name country name default i want display from database . i have created database its connected via ajax code above code i had mentioned.
here attach my php code :
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydatabase";
$_country = $_GET['country'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT countryId,country,pdogcoregion,ccl,category FROM countrydetails WHERE country='".$_country."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "category: " . $row["category"];
}
}
else {
echo "No database";
}
$conn->close();
?>
I need to change the label showing country name default.
I want set database display label ?
You can customise tooltip using onRegionTipShow method. Just take a look at example available here.