I am trying to create a Google area chart in model using AJAX. If I use the response from the AJAX request then the Google Chart doesn't work. If I use default values, then it works. Where is the problem? Thanks in advance.
function showDetails(REPORTNO, date1, date2, locid, cancelId) {
$.ajax({
url: "catdetail.php",
method: "POST",
async: true,
data: {
"REPORTNO": REPORTNO,
"date1": date1,
"date2": date2,
"locid": locid,
"cancelId": cancelId
},
success: function(response) {
var qty = "";
details = JSON.parse(response);
$.each(details, function(i) {
res = details[i];
timeord = res[0];
catqty = res[1];
qty += "['" + timeord + "'," + catqty + "],";
})
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
alert(qty);
var data = google.visualization.arrayToDataTable([
['Time', 'Qty'],
//['1', 12],['2', 12],['3', 12],['4', 12],['5', 12]
qty
]);
var options = {
title: 'Company Performance',
hAxis: {
title: 'Category Sales by Time',
titleTextStyle: {
color: '#333'
}
},
vAxis: {
minValue: 0
},
pointSize: 18,
pointShape: {
type: 'star',
sides: 5,
dent: 0.5
}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_detail'));
chart.draw(data, options);
}
}
});
};
<div id="chart_detail" style="width: 100%; height: 500px"></div>
since you're sending an array in json format,
you do not need to rebuild the array on the client.
you only need to add the column headings. (which could probably be done in php as well)
success: function(response) {
var details = JSON.parse(response);
details.ushift(['Time', 'Qty']);
then use details to create the data table.
var data = google.visualization.arrayToDataTable(details);
see following snippet...
function showDetails(REPORTNO, date1, date2, locid, cancelId) {
$.ajax({
url: "catdetail.php",
method: "POST",
async: true,
data: {
"REPORTNO": REPORTNO,
"date1": date1,
"date2": date2,
"locid": locid,
"cancelId": cancelId
},
success: function(response) {
var details = JSON.parse(response);
details.ushift(['Time', 'Qty']);
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable(details);
var options = {
title: 'Company Performance',
hAxis: {
title: 'Category Sales by Time',
titleTextStyle: {
color: '#333'
}
},
vAxis: {
minValue: 0
},
pointSize: 18,
pointShape: {
type: 'star',
sides: 5,
dent: 0.5
}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_detail'));
chart.draw(data, options);
});
}
});
};
Related
I am trying to poll my data in HighCharts. The graph in this link is what I am trying to achieve. I am using Ajax request to retrieve my data. Here is my code:
setInterval(RefreshGraph, 3000);
...
...
function RefreshGraph() {
var options = {
chart: {
type: 'spline'
},
title: {
text: 'Text'
},
xAxis: {
title: {
text: 'TIMEFRAME'
},
categories: ['-4m', '-3m', '-2m', '-1m', 'Now']
},
yAxis: {
title: {
text: 'NUMBER'
},
},
tooltip: {
crosshairs: true,
shared: true
},
plotOptions: {
spline: {
marker: {
radius: 4,
lineColor: '#666666',
lineWidth: 2
}
}
},
series: [{}]
};
Highcharts.ajax({
url: "/Home/GetData",
success: function (data) {
var formattedData = FormatData(data);
//Graph 1
options.series[0] = formattedData[0];
//Graph 2
options.series[1] = formattedData[1];
Highcharts.chart("container", options);
}
});
}
However, the entire graph gets redrawn with my above code. How can I enable live polling for the above code?
You create a chart every time data is received. You need to create a chart and then update it. Example:
const options = {...};
const chart = Highcharts.chart("container", options);
function RefreshGraph() {
Highcharts.ajax({
url: "/Home/GetData",
success: function(data) {
var formattedData = FormatData(data);
chart.update({
series: [formattedData[0], formattedData[1]]
});
}
});
}
setInterval(RefreshGraph, 3000);
Live demo: http://jsfiddle.net/BlackLabel/6d5stjab/
API Reference: https://api.highcharts.com/class-reference/Highcharts.Chart#update
I have a chart and my system that I need it to report the exact value of the search results.
Due to many data, the results come out so 1.1K.
In the place that 1.1K wanted it shows the exact value that would be 1057.
Here is the graph function in JS:
function Post(url, param, title, totalText) {
totalText = totalText || "Total";
$.ajax({
method: "POST",
url: "/Graficos/" + url,
data: param,
beforeSend: function () {
showLoader();
},
success: function (data) {
ChartConstructor(title, JSON.stringify(data), totalText);
},
complete: function () {
hideLoader();
}
});
}
function ChartConstructor(title, dados, totalText) {
window.google.charts.load('current', { 'packages': ['bar'] });
window.google.charts.setOnLoadCallback(drawStuff);
function drawStuff() {
var table = JSON.parse(dados);
var rows = "";
var array = [["", "Total"]];
for (var i = 0; i < table.length; i++) {
array.push([table[i].Title, table[i].Count]);
}
var data = new google.visualization.arrayToDataTable(array);
var options = {
width: '100%',
height: 400,
chart: {
title: title,
},
bar: { groupWidth: '95%' },
bars: 'horizontal',
series: {
0: { axis: 'distance' },
}
};
var chart = new google.charts.Bar(document.getElementById("chart-content"));
chart.draw(data, options);
$("#chart-type").val("");
}
}
According to the documentation, you can set the format of hAxis or vAxis to 'none' to display the full number.
Example:
var options = {
width: '100%',
height: 400,
chart: {
title: title,
},
bar: { groupWidth: '95%' },
bars: 'horizontal',
series: {
0: { axis: 'distance' },
},
vAxis: {
format: 'none'
}
};
I have code like this
public static string summarydata(string RegNo)
{
try
{
TrackDataEntities1 sd = new TrackDataEntities1();
var mdata = new TrackDataEntities1().spsumdata(RegNo)
.Select(s => new { month = s.Month }).ToArray();
var sdata = new TrackDataEntities1().spsumdata(RegNo)
.Select(s => new { s.VName, s.total }).ToArray();
return Newtonsoft.Json.JsonConvert.SerializeObject(mdata) + "*" + Newtonsoft.Json.JsonConvert.SerializeObject(sdata);
}
catch (Exception)
{
throw new Exception();
}
}
now this return me data like this
"[{\"month\":\"July\"},{\"month\":\"June\"},{\"month\":\"June\"},
{\"month\":\"August\"},{\"month\":\"July\"},{\"month\":\"June\"},
{\"month\":\"May\"},{\"month\":\"June\"}]*[{\"VName\":\"DDSB\",\"total\":1},
{\"VName\":\"DPSB\",\"total\":1},{\"VName\":\"DSB\",\"total\":1},
{\"VName\":\"MV\",\"total\":5},{\"VName\":\"MV\",\"total\":11},
{\"VName\":\"MV\",\"total\":7},{\"VName\":\"MV\",\"total\":1},
{\"VName\":\"PSB\",\"total\":1}]"
jquery
UPDATED JQUERY
$(function () {
$('#tabledata').on('click', 'tr', function () {
var row = $(this);
var regno = row.find('td')[0].firstChild.data;
var obj = {};
obj.RegNo = regno;
Getsumdata(obj);
return false;
});
});
function Getsumdata(obj) {
$.ajax({
type: "POST",
url: "WebForm1.aspx/summarydata",
data: JSON.stringify(obj),
contentType: "application/json;charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (result) {
alert(JSON.stringify(result.d));
var data1 = result.d.split('*')[0];
console.log(typeof (data1)); //Still a String...
var data11 = JSON.parse(data1);
console.log(data11); //
$('#sum').highcharts({
title: {
text: 'Combination chart'
},
xAxis: {
categories: data11,
title: {
text: null
}
},
labels: {
items: [{
html: 'Total fruit consumption',
style: {
left: '50px',
top: '18px',
color: (Highcharts.theme && Highcharts.theme.textColor) || 'black'
}
}]
},
// series:data2
series: [{
type: 'column',
name: 'Jane',
data: [3, 2, 1, 3, 4]
}, {
type: 'column',
name: 'John',
data: [2, 3, 5, 7, 6]
}, {
type: 'column',
name: 'Joe',
data: [4, 3, 3, 9, 0]
},
]
});
}
});
}
</script>
but chart look like this
Now the question is JSON look correct i think so why data is not populated in chart .. i use BAR highchart
any solution please?
data2 is still a string, you have to parse it.
Take a look at the Docs on how to add chart data, you have to transform your current data.
var a = "[{\"month\":\"July\"},{\"month\":\"June\"},{\"month\":\"June\"}, {\"month\":\"August\"},{\"month\":\"July\"},{\"month\":\"June\"}, {\"month\":\"May\"},{\"month\":\"June\"}]*[{\"VName\":\"DDSB\",\"total\":1}, {\"VName\":\"DPSB\",\"total\":1},{\"VName\":\"DSB\",\"total\":1}, {\"VName\":\"MV\",\"total\":5},{\"VName\":\"MV\",\"total\":11}, {\"VName\":\"MV\",\"total\":7},{\"VName\":\"MV\",\"total\":1}, {\"VName\":\"PSB\",\"total\":1}]";
var d = a.split('*')[1];
console.log(typeof(d)); //Still a String...
var e = JSON.parse(d);
console.log(e); //Yay an object.
It seems that you are not passing correct data to categories and series's.
Please transform your data in such a way that,
data1 represent categories, should look like this
["May","June","July","August"]
while your data2 represent the series data which you want to plot for a given month, should look like below.
[1,10,12,5]
I met with a problem on HighCharts.
I had to gather data from a xml content with ajax in order to draw it in a HighCharts chart.
I get my datas. I can see my points when I move my mouse over it but my chart is not displaying anything.
A picture to see the problem :
mouse over the third point
And some parts from my code if it can help :
var myData=[];
function makeChart() {
var chart;
$(document).ready(function () {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container2',
type: 'spline',
borderColor: '#DC143C',
borderRadius: 20,
borderWidth: 2,
marginRight: 130,
marginBottom: 25
},
title: {
text: ''
},
xAxis: {
categories :[0,1,2,3,4,5]
},
yAxis: {
title: {
text: 'Values'
},
},
series: [{
color: '#FF00FF',
name: '',
data: myData
}]
});
});
}
$(function (){
$(document).ready(function ping(){
ChartDeOuf();
makeChart();
$.ajax({
type: "GET",
url: 'http://localhost:8080/SASI/runSimulation',
dataType: "xml",
success: function(result){
var i = 0;
var xmlDoc = $.parseXML(result);
var chart = $('#container2').highcharts();
$result = $(xmlDoc);
$(result).find('measure').each(function(){
var $value = $(this);
var attr = $value.attr("meanValue");
myData[i]=attr;
var html = '<p> '+myData[i]+'</p>';
chart.series[0].addPoint({y: myData[i]},false);
chart.redraw();
$('body').append($(html));
i++;
})
},
error: function(result){
alert('timeout/error');
}
});
});
});
Thanks for reading.
Got it, that line saved everything :
myData[i]=parseFloat(attr);
My code successfully draws a chart with data and tick labels retrieved as JSON object from PHP. Now at one point i want to refresh the chart but with slightly different data and different tick labels without creating a new chart.
$.jqplot.config.enablePlugins = true;
var freqs1 = [];
var freqlabels1 = [];
var dataRendered1 = $.ajax({
async: false,
url: 'MY_URL',
dataType: 'json',
success: function(data) {
if (data.length) {
freqs1 = data[0];
freqlabels1 = data[1];
}
}
});
var plot1 = $.jqplot('chartdiv', [freqs1], {
animate: !$.jqplot.use_excanvas,
seriesDefaults:{
renderer:$.jqplot.BarRenderer,
pointLabels: {
show: true
},
rendererOptions: {
barWidth: 12
}
},
title:'Test',
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: freqlabels1,
label: "Test 1",
tickOptions:{textColor : 'rgb(39, 125, 175)', fontSize: '9pt'}
},
yaxis: {
label: "Test 2",
labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
tickOptions:{textColor : 'rgb(39, 125, 175)', fontSize: '9pt'}
}
},
highlighter: { show: true }
});
now when button is clicked lets say I have an ajax call that gets the new data and tick labels
$(document).on('click', '#refresh_new', function() {
$.ajax({
async: false,
url: 'MY_URL',
dataType: 'json',
success: function(data) {
var newData = data[0];
var newTicks = data[1];
//HOW DO I REFRESH CHART WITH NEW DATA AND TICKS FOR x-AXIS
}
});
});