C3 chart with JSON data - javascript

I am trying to populate a C3 chart with dynamic data from a SQL database. I have c# web method that when called by my javascript produces the following JSON string
[{"y":"5","item1":"Lion Wharf"},{"y":"31","item1":"Millbrook Park P2"},{"y":"84","item1":"Pinfield Meadows"}]
I'm using the following javascript on pageload but getting error "a.forEach is not a function"
$.ajax({
type: "POST",
url: "additions.aspx/GetPiechartData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "true",
cache: "false",
success: function (result) {
OnSuccess(result.d);
},
error: function (xhr, status, error) {
alert(error);
}
});
function OnSuccess(response) {
var abc = JSON.stringify(response);
window.location.replace(response);
var chart = c3.generate({
bindto: '#chart-var-project',
data: {
json: response,
keys: {
x: 'y',
value: ['item1']
},
type: 'donut'
},
donut: {
title: "Approval",
width: 40,
label: {
show: false
}
},
color: {
pattern: ["#ff9800", "#78c350", "#f7531f"]
}
});
I'm very new to Javascript and would really appreciate a pointer here
Thanks!

You have to format your json response to fit the expected format of C3 for Donut graph type.
function OnSuccess(response) {
var data = {};
var value = [];
JSON.parse(response).forEach(function(d) {
data[d.item1] = d.y;
value.push(d.item1);
});
c3.generate({
data: {
json: [data],
keys: {
value : value
},
type: 'donut'
},
donut: {
title: "Approval",
width: 40,
label: {
show: false
}
},
color: {
pattern: ["#ff9800", "#78c350", "#f7531f"]
}
})
}
Your server will normally output a string, so using a JSON.parse will transform this string into a json object.

function OnSuccess(response) {
var jsonData = response.d;
var chart = c3.generate({
bindto: '#chart-var-project',
data: {
json: JSON.parse(jsonData),
}
});
}

Related

Apexcharts remove old data series before render new series

I'm using apex chart for simple data visualization from json output. My charts based on pure javascript and not Vue or other frameworks.
My json (php) backend create two json outputs fro draw the chart as below
JSON 1
{
"x": "2019-05-27 16:18:48",
"y": "100"
},
{
"x": "2019-05-27 16:25:09",
"y": "110"
},
JSON 2
{
"x": "2019-05-27 16:18:48",
"y": "60"
},
{
"x": "2019-05-27 16:25:09",
"y": "65"
},
Based on the above two json outputs I retrieve data and draw my graph using the Category paired values method. below is the code responsible for retrieve data and draw the chart.
function for getting json data
function data_function(){
$.ajax({
type: "Get",
url: backend,
data:{
param: "all_a"
},
async: true,
cache: false,
success: function(data) {
a_data = data;
$.ajax({
apex_task: "Get",
url: backend,
data:{
param: "all_b"
},
async: true,
cache: false,
success: function(data) {
b_data = data;
chart(a_data,b_data);
}
});
}
});
}
function for draw chart
function draw_chart(a_data,b_data) {
var options = {
chart: {
height: 400,
type: 'bar',
stacked: false
},
series: [
{
name: 'a',
data: a_data,
},
{
name: 'b',
data: b_data,
}],
yaxis: [
{
axisTicks: {
show: true,
},
axisBorder: {
show: true,
color: '#008FFB'
},
labels: {
style: {
color: '#008FFB',
}
}
},
]
}
var chart = new ApexCharts(document.querySelector("#chartdiv"), options);
chart.render();
}
This works fine until I second time render the chart with new data. when I load the different data without reloading the windows chart happen to be laggy and render multiple times with the old incorrect data. sometimes I have to run the data_fnction multiple times to render the chart properly.
How can I fix this? Do I need to use function like appendchart ? how can I use wiht my data_function
You should call the render() method just once in the beginning (even with empty array it should work), then call the updateSeries() method in ajax call to update data of the chart.
var options = {
chart: {
height: 400,
type: 'bar',
stacked: false
},
series: [],
yaxis: [{
axisTicks: {
show: true,
},
axisBorder: {
show: true,
color: '#008FFB'
},
labels: {
style: {
color: '#008FFB',
}
}
}]
}
var chart = new ApexCharts(document.querySelector("#chartdiv"), options);
chart.render();
Your ajax call with updateSeries method of the chart
function data_function() {
$.ajax({
type: "Get",
url: backend,
data: {
param: "all_a"
},
async: true,
cache: false,
success: function (data) {
a_data = data;
$.ajax({
apex_task: "Get",
url: backend,
data: {
param: "all_b"
},
async: true,
cache: false,
success: function (data) {
b_data = data;
chart.updateSeries([{
name: 'a',
data: a_data
}, {
name: 'b',
data: b_data
}])
}
});
}
});
}
Docs for updateSeries
Although there is the updateSeries function, you're allowed to render again the values of the chart by destroying the previous ones. This works with ApexCharts, ChartJS, etc.
var options =
{
series: [],
chart:
{
type: 'donut',
height: 150
},
labels: ['...'],
};
// Destroy if exists in order to re-update the data
if (window.myChart)
window.myChart.destroy();
window.myChart = new ApexCharts(chart, options);
window.myChart.render();

DataTables column data convert properly

this is what i look at
and this is what i received from server
function requestData() {
$.ajax({
url: "<c:url value='/abs/guide/guideSampleChartData1Ajax.do'/>",
type: "GET",
dataType: "json",
success: function(data) {
for(var i in data) {
chart.addSeries({
name: data[i].name,
data: data[i].data
});
}
console.log(data);
$("#table").dataTable({
"data": data,
"columns": [
{ "data": "name" },
{ "data": "categData" },
{ "data": "data"}
]
});
}
});
}
and this is my code, i want to my datatables looking accordingly
so, what part of code, i change??

display a linear highchart with data from database

i'm trying to display data from database into a linear highchart. this is the json response from my controller which is retrieved from database:
[{"protocole":"tcp","date":"01/02/20","time":"00:10:20","total":281},
{"protocole":"udp","date":"01/02/20","time":"00:10:30","total":201},
{"protocole":"tcp","date":"01/02/20","time":"00:10:40","total":100}}
i succeeded to display data in the yAxix from data base but i've tested it with static data in the xAxix this is the code :
$(document).ready(function() {
var options={
chart: {
renderTo: 'container',
type: 'line'
},
title : {
text: 'Total Request number'
},
subtitle : {
text: 'Server num1'
},
xAxis : {
categories: ['00:10:20','00:10:30','00:10:40']
},
yAxis :{
title: {
text: 'Total'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip : {
valueSuffix: '\xB0C'
},
legend : {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series : [{}]
}
$.ajax({
type: 'GET',
contentType : 'application/json',
dataType: 'JSON',
url: 'jsonsdp',
data: "",
success: function(data){
var array=[] ;
$.each(data, function(i) {
array.push(data[i].total);
})
alert(array);
options.series[0]= {"name": 'total',
"data":array};
var chart = new Highcharts.Chart(options);
}
});
});
now i want the categories to be dynamic and retrieve time and put it on axis .
I have tried this code but still not working !
$.ajax({
type: 'GET',
contentType : 'application/json',
dataType: 'JSON',
url: 'jsonsdp',
data: "",
success: function(data){
var array=[] ;
var array1=[];
$.each(data, function(i) {
array.push(data[i].total);
array1.push(data[i].time);
})
// alert(array);
options.series[0]= {"name": 'total',
"data":array};
options.xAxis.categories=array1;
var chart = new Highcharts.Chart(options);
}
});
do somebody have an idea how to do this ?
thanks in advance .
I've tested this code and it works perfectly !
I don't know why this didn't work for the first time and showed errors and now works !
I post it maybe it could help someOne. if someone knows why it will be better to mention it .
$.ajax({
type: 'GET',
contentType : 'application/json',
dataType: 'JSON',
url: 'jsonsdp',
data: "",
success: function(data){
var array=[] ;
var array1=[];
$.each(data, function(i) {
array.push(data[i].total);
array1.push(data[i].time);
})
// alert(array);
options.series[0]= {"name": 'total',
"data":array};
options.xAxis.categories=array1;
var chart = new Highcharts.Chart(options);
}
});

How to Populate Highchart using Json Object

I am trying to populate highchart from server side using json object.frankly speaking I have average knowledge of jquery and highchart. I am newbie in json, jquery and highchart.
I am able to receive the json object from server side but facing issue while populating highchart.
can any body help me with this.
my json object receive from server look like this
[Object { year=2001, populations=10000}, Object { year=2002, populations=20000}, Object { year=2003, populations=30000}, Object { year=2004, populations=40000}, Object { year=2005, populations=50000}, Object { year=2006, populations=60000}, Object { year=2007, populations=70000}]
my script to populate the highchart is
$(document).ready(function () {
$.ajax({
type: "GET",
url: 'dispatcherServlet/reportController/getreport',
dataType: "json",
contentType: "application/json",
crossDomain: true,
success: function (data) {
console.log(data);
var name = Array();
var value = Array();
var dataArrayFinal = Array();
for (i = 0; i < data.length; i++) {
name[i] = data[i].year;
value[i] = data[i].populations;
}
for (var j = 0; j < name.length; j++) {
var temp = new Array(name[j], value[j]);
dataArrayFinal[j] = temp;
}
// draw chart
$('#container').highcharts({
chart: {
type: "column"
},
title: {
text: "City Population"
},
xAxis: {
allowDecimals: false,
title: {
text: "Year"
}
},
yAxis: {
title: {
text: "Population",
data: value[i].year
}
},
series: [{
data: dataArrayFinal
}]
});
}
});
});
When I am simply passing my data receive from server to highchart series. I am getting balnk highchart.
The second script look like this
$(document).ready(function () {
$.ajax({
type: "GET",
url: '/dispatcherServlet/reportController/getreport',
dataType: "json",
contentType: "application/json",
crossDomain: true,
success: function (data) {
console.log(data);
for (var i = 0; i < data.length; i++) {
// alert(data[i].year);
// alert(data[i].populations);
// draw chart
$('#container').highcharts({
chart: {
type: "column"
},
title: {
text: "City Population"
},
xAxis: {
allowDecimals: false,
title: {
text: "Year"
}
},
yAxis: {
title: {
text: "Population",
}
},
series: [{
data: data
}]
});
}
}
});
});
Finally it worked
$(document).ready(function () {
$.ajax({
type: "GET",
url: '/dispatcherServlet/reportController/getreport',
dataType: "json",
contentType: "application/json",
crossDomain: true,
success: function (data) {
console.log(data);
// Populate series
var processed_json = new Array();
for (i = 0; i < data.length; i++) {
processed_json.push([data[i].year, parseInt(data[i].populations)]);
}
// draw chart
$('#container').highcharts({
chart: {
type: "column"
},
title: {
text: "City Population"
},
xAxis: {
allowDecimals: false,
title: {
text: "Year"
}
},
yAxis: {
title: {
text: "Population"
}
},
series: [{
data: processed_json
}]
});
}
});
});
[ { "year":2001, "populations":10000},
{ "year":2002,"populations":20000},
{ "year":2003, "populations":30000},
{ "year":2004, "populations":40000},
{ "year":2005, "populations":50000},
{ "year":2006, "populations":60000},
{ "year":2007, "populations":70000}
]
var title = prompt("Please enter Title of your Chart: ", "");
// var chart = $('#container').highcharts();
var x=new Array();
//var product = prompt("Please enter Column Name: ", "");
var stock = prompt("Please enter Y Axis Name: ", "");
//var name = prompt("Please enter Series Name: ", "");
$(function () {
var text="Stock Level";
var y=new Array();
var attr="";
var processed_json = new Array();
$.getJSON('data2.json', function(data) { //Getting data from JSON file
//var keys=new Array();
var obj=JSON.stringify(data[1]);
//alert(obj);
attr=JSON.stringify(obj.substring(2,obj.indexOf(":")-1))
//alert(JSON.stringify(obj.substring(2,obj.indexOf(":")-1)));
var attr1=attr.substring(1,attr.length-1);
//alert(attr1);
//alert(attr1);
$.each(data, function(key, value)
{
// var yName="Stock";
//var product="ProductId";
var idd=value[attr1];
//Getting Values of 1st Attribute that has to be represented along X-axis
x.push(idd);
//Getting Values of 2nd attribute that has to be represented along Y-axis
y.push(value.populations);
//$("ul").append("<li>"+value.ProductId+" "+value.Stocklevel+"<li>")
});
// draw chart
$('#container').highcharts({
chart: {
type: "column"
},
title: {
text: title
},
xAxis: {
categories: x, //Populating X-axis
type: 'category',
allowDecimals: false,
title: {
text: ""
}
},
yAxis: {
title: {
text: stock
}
},
series: [
{
name: name ,
data:y //Populating Y-axis
}
]
});
});
});

values not updated after an ajax response

I am sending some form data via ajax to a php script in the same page. PHP must process the data and show results in the same page.
I am using this syntax for ajax:
$.ajax
({
type: "POST",
url: "",
data: $("form").serialize(),
success: function(result)
{
updatechart();
console.log(result);
}
});
I am basically trying to update some values in a chart based on data entered in the form and after processed by a php script. I get the whole source of the page when I do console.log(result); and the values are updated in my console after doing this but the chart is not updated. When I view-source the page, the values remain the same. What should I do?
function updatechart() {
var json=<?php echo json_encode($GLOBALS['json']); ?>;
var direct=json['direct'];
var total=json['total'];
var referred=total-direct;
var aid=new Array();
var count=new Array();
for(var i=0;i<json['aid'].length;i++) {
aid[i]=json['aid'][i];
count[i]=json['count'][i];
}
var series = [{
name : "Referred",
data: [referred]
}, {
name: "Direct",
data: [direct]
}];
for(var i=0; i<aid.length;i++) {
series.push({
name: 'AID-'+[aid[i]],
data: [count[i]]
})
}
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'User Source Chart'
},
xAxis: {
categories: ['Users']
},
yAxis: {
min: 0,
title: {
text: 'Total users'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.percentage:.0f}%)<br/>',
shared: true
},
plotOptions: {
column: {
stacking: 'percent'
}
},
series: series
};
chart = new Highcharts.Chart(options);
}
This is my updatechart() code. The problem is, json value is not updated.
Pass the result as parameter to updatechart()
$.ajax
({
type: "POST",
url: "",
data: $("form").serialize(),
success: function(result)
{
updatechart(result);
}
});
then access the results via parameter.
function updatechart(result) {
//.......
//.......
console.log(result);
}
Hope you're trying something like this.
That is expected behavior. Move your PHP processing to a different page.
$.ajax
({
type: "POST",
url: "anotherphppage.php",
data: $("form").serialize(),
success: function(result)
{
updatechart(result);
}
});
Try this and you'll see what I mean:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#mybutt').click(function() {
$.ajax({
type: "POST",
url: "",
data: 'myVar=Hello',
success: function(data) {
alert(data);
}
});
});
}); //END $(document).ready()
</script>
</head>
<body>
Try this:<br />
<input type="button" id="mybutt" value="Click Me">
</body>
</html>

Categories

Resources