chart.data from ajax call function - javascript

I wanna make a chart with amCharts and have some values that I've recieved from server by ajax call.
now I want to use that data for my chart
can anyone tell me how can i do so?
var chart = am4core.create("chartdiv", am4charts.XYChart);
// Add data
chart.data= (dont want to add data by myself)
// Add and configure Series
var pieSeries = chart.series.push(new am4charts.PieSeries());
pieSeries.dataFields.value = "SalePrd";
pieSeries.dataFields.category = "SaleYear";
and data call code
var Ajax_URL= url;
var Year_Val = GetSelectValue("YearSelect");
var Prd_Val = GetSelectValue("PrdSelect");
app.request.get(Ajax_URL, { "Token": Token_Data, "SaleYear":Year_Val, "SalePrd":Prd_Val }, function (data)
{
var data_Str=''+data;
var data_Output = JSON.parse(data_Str);
return data_Output;
});
}

make the ajax call,
then draw the chart when the data is returned...
var Ajax_URL= url;
var Year_Val = GetSelectValue("YearSelect");
var Prd_Val = GetSelectValue("PrdSelect");
app.request.get(Ajax_URL, { "Token": Token_Data, "SaleYear":Year_Val, "SalePrd":Prd_Val }, function (data)
{
var data_Str=''+data;
var data_Output = JSON.parse(data_Str);
var chart = am4core.create("chartdiv", am4charts.XYChart);
// Add data
chart.data = data_Output;
// Add and configure Series
var pieSeries = chart.series.push(new am4charts.PieSeries());
pieSeries.dataFields.value = "SalePrd";
pieSeries.dataFields.category = "SaleYear";
});

Related

How do i can add custom html tags in am-chart (map-chart)

I am trying to add custom html <a href="state/alaseka"><a> on each state of america as shown in map example out put would be something like this site "https://covidactnow.org/?s=1311324" and i am trying this as follow
Javascript
am4core.ready(function() {
function am4themes_myTheme(target) {
if (target instanceof am4core.ColorSet) {
target.list = [
am4core.color("#ff3b37")
];
}
}
// Themes begin
am4core.useTheme(am4themes_myTheme);
// Themes end
// Create map instance
var chart = am4core.create("usstatemap", am4maps.MapChart);
// Set map definition
chart.geodata = am4geodata_usaLow;
// Set projection
chart.projection = new am4maps.projections.AlbersUsa();
var polygonSeries = chart.series.push(new am4maps.MapPolygonSeries());
// Create map polygon series polygonSeries
//Set min/max fill color for each area
polygonSeries.heatRules.push({
property: "fill",
target: polygonSeries.mapPolygons.template,
min: chart.colors.getIndex(1).brighten(-0.3),
max: chart.colors.getIndex(1).brighten(1)
});
// Make map load polygon data (state shapes and names) from GeoJSON
polygonSeries.useGeodata = true;
stateName = {{ allStateName | safe }}
statePopulation = {{ allStatePopulation | safe }}
console.log("==========================act casess keyindicator3 =====================")
console.log(actcase)
var data = [];
var id = "";
var value = "";
var expenses = "";
for(var i = 0; i < stateName.length; i++){
year =actdate[i]
//e.,g "US-"+actdate[i]
id ="US-"+actdate[i];
url="http://127.0.0.1:8000/states/"+actdate[i]
value = actdeath[i];
console.log(url);
data.push({id:id, value:value,url:url});
}
console.log("==== state from us ap =======\t\t\t",data)
// Set heatmap values for each state
polygonSeries.data = data;
chart.events.on( "ready", updateCustomMarkers );
chart.events.on( "mappositionchanged", updateCustomMarkers );
// this function will take current images on the map and create HTML elements for them
function updateCustomMarkers( event ) {
// go through all of the images
polygonSeries.MapPolygon.each(function(image) {
// check if it has corresponding HTML element
if (!image.dummyData || !image.dummyData.externalElement) {
// create onex
image.dummyData = {
externalElement: createCustomMarker(image)
};
}
// reposition the element accoridng to coordinates
var xy = chart.geoPointToSVG( { longitude: image.longitude, latitude: image.latitude } );
image.dummyData.externalElement.style.top = xy.y + 'px';
image.dummyData.externalElement.style.left = xy.x + 'px';
});
}
// this function creates and returns a new marker element
function createCustomMarker( image ) {
var chart = image.dataItem.component.chart;
// create holder
var holder = document.createElement( 'a' );
holder.className = 'map-marker';
holder.title = image.dataItem.dataContext.title;
holder.style.position = 'absolute';
holder.href = 'www.google.com';
holder.target = '_parent';
// maybe add a link to it?
if ( undefined != image.url ) {
holder.onclick = function() {
window.location.href = image.url;
};
holder.className += 'map-clickable';
}
}//Set up heat legend
heatLegend = chart.createChild(am4maps.HeatLegend);
heatLegend.series = polygonSeries;
heatLegend.align = "right";
heatLegend.valign = "bottom";
heatLegend.width = am4core.percent(20);
heatLegend.marginRight = am4core.percent(4);
heatLegend.minValue = 0;
heatLegend.maxValue = 400000;
// Set up custom heat map legend labels using axis ranges
var minRange = heatLegend.valueAxis.axisRanges.create();
minRange.value = heatLegend.minValue;
minRange.label.text = "min";
var maxRange = heatLegend.valueAxis.axisRanges.create();
maxRange.value = heatLegend.maxValue;
maxRange.label.text = "max";// Set up custom heat map legend labels using axis ranges
// Blank out internal heat legend value axis labels
heatLegend.valueAxis.renderer.labels.template.adapter.add("text", function(labelText) {
return "";
});
// Configure series tooltip
var polygonTemplate = polygonSeries.mapPolygons.template;
polygonTemplate.tooltipText = "{name}: {value}";
polygonTemplate.nonScalingStroke = true;
polygonTemplate.strokeWidth = 0.5;
// Create hover state and set alternative fill color
var hs = polygonTemplate.states.create("hover");
hs.properties.fill = am4core.color("#3c5bdc");
});
Note:
i have used my data you can use the data from the amchart as link mentioned bellow for dummy data to be used and i am following exactly the same chart as in the link,
https://www.amcharts.com/demos/us-heat-map/
i have resolve this question by adding this simple one line in the above code
polygonTemplate.propertyFields.url = "url";
to make this work you have to add the URL for each state into the data series object

how to capture all data from spreadsheet to google form

here's my code and i already input loop command but it only can capture the first row from spreadsheet to google form response.
i need to capture all data from spreadsheet when i execute the code.
anyone know what im missing ?
function auto_data() {
var formURL="https://docs.google.com/forms/d/e/1FAIpQLSec8kePcCeGY0vlq3FdIepQgE84Wh7DiYE1e0v7ZWvo5XhxoQ/formResponse";
var wrkBK = SpreadsheetApp.getActiveSpreadsheet();
var wrkSht= wrkBK.getSheetByName("Sheet1");
for (var i=2;i<=5;i++){
var a = wrkSht.getRange('A'+i).getDisplayValue();
var b = wrkSht.getRange('B'+i).getDisplayValue();
var c = wrkSht.getRange('C'+i).getDisplayValue();
}
var datamap = {"entry.1436037797":a,
"entry.995641845":b,
"entry.1420146463":c};
var options = {
"method":"post",
"payload": datamap };
UrlFetchApp.fetch(formURL, options);
}
move your fetch(..) call and payload composition into the for loop:
function auto_data() {
var formURL="https://docs.google.com/forms/d/e/1FAIpQLSec8kePcCeGY0vlq3FdIepQgE84Wh7DiYE1e0v7ZWvo5XhxoQ/formResponse";
var wrkBK = SpreadsheetApp.getActiveSpreadsheet();
var wrkSht= wrkBK.getSheetByName("Sheet1");
for (var i=2;i<=5;i++){
var a = wrkSht.getRange('A'+i).getDisplayValue();
var b = wrkSht.getRange('B'+i).getDisplayValue();
var c = wrkSht.getRange('C'+i).getDisplayValue();
var datamap = {"entry.1436037797":a,
"entry.995641845":b,
"entry.1420146463":c};
var options = {
"method":"post",
"payload": datamap };
UrlFetchApp.fetch(formURL, options);
}
}

Chart JS always failed to load labels or legends when using ajax request

My Chart JS always failed to showing labels or legends when the data is from ajax response, The data is showing up but the legend always failed, I created my labels manually and assign it one by one but it's still doesn't work and ended up with error like Uncaught TypeError: Cannot read property 'fontSize' of undefined, but when i change the chart type to pie or doughnut, my chart is working but still the legends or labels is not showing up.
here's my code :
function getChartData() {
$.ajax({
dataType: 'JSON',
method: 'POST',
cache: false,
url: '<?php base_url()?>/Rest_API/someurl',
}).done(function(data){
var timeseries = data['result']['timeseries'];
var d1 = timeseries['0']['uniques']['all'];
var d2 = timeseries['1']['uniques']['all'];
var d3 = timeseries['2']['uniques']['all'];
var d4 = timeseries['3']['uniques']['all'];
var d5 = timeseries['4']['uniques']['all'];
var d6 = timeseries['5']['uniques']['all'];
var d7 = timeseries['6']['uniques']['all'];
var l1 = timeseries['0']['since']
var l2 = timeseries['1']['since']
var l3 = timeseries['2']['since']
var l4 = timeseries['3']['since']
var l5 = timeseries['4']['since']
var l6 = timeseries['5']['since']
var l7 = timeseries['6']['since']
var chartdata = [d1,d2,d3,d4,d5,d6,d7];
var chartlabels = [l1,l2,l3,l4,l5,l6,l7]
//Create the chart.js data structure using 'labels' and 'data'
var tempData = {
labels : chartlabels,
datasets : [{
data : chartdata
}]
};
var ctx = document.getElementById("chartPageRequest").getContext('2d');
var myLineChart = new Chart(ctx).Line(tempData, {
});
});
}
<div class="GrafikchartPageRequest">
<canvas id="chartPageRequest"></canvas>
</div>
and just for testing, I change my data and label manually inside the ajax done function like above :
var tempData = {
labels : ["1","2","3","4"],
datasets : [{
data : [4,5,6,7]
}]
};
var ctx = document.getElementById("chartPageRequest").getContext('2d');
var myLineChart = new Chart(ctx).Line(tempData, {
});
but still thrown an error Uncaught TypeError: Cannot read property 'fontSize' of undefined that's mean the legends is failed to showing up. Thank you.
UPDATE : AJAX RESPONSE

Remove bank holidays from X Axis by amchart

I have data by date like this there is no 2017/07/17,2017/07/16,2017/07/15
because they are bank holidays.
chartData = new Array();
chartData[0] = new Array();
chartData[0].closePrice = 1207;
chartData[0].date = new Date("2017/07/12");
chartData[1] = new Array();
chartData[1].closePrice = 1227;
chartData[1].date = new Date("2017/07/13");
chartData[2] = new Array();
chartData[2].closePrice = 1216;
chartData[2].date = new Date("2017/07/14");
chartData[3] = new Array();
chartData[3].closePrice = 1234;
chartData[3].date = new Date("2017/07/18");
I use this chartData as dataProvider for making graph.
var dataSet = new AmCharts.DataSet();
dataSet.dataProvider = chartData;
dataSet.categoryField = "date";
chart.dataSets = [dataSet];
var stockPanel = new AmCharts.StockPanel();
stockPanel.title = "Stock Main";
stockPanel.id = "stockPanel";
stockPanel.showCategoryAxis = false;
stockPanel.recalculateToPercents = "never";
var valueAxis = new AmCharts.ValueAxis();
valueAxis.dashLength = 5;
stockPanel.addValueAxis(valueAxis);
stockPanel.categoryAxis.dashLength = 5;
stockPanel.categoryAxis.equalSpacing = true; // it doesn't work ....
var graph = new AmCharts.StockGraph();
graph.type = "line";
graph.valueField = "closePrice";
stockPanel.addStockGraph(graph);
however 2017/07/15,2017/07/16 2017/07/16 are drawn on X axis , even there are no data.
Even .equalSpacing looks in vain.
How can I remove this???
You have to set equalSpacing in the categoryAxesSettings property in the stock chart for it to work.
//object-based setup
chart.categoryAxesSettings = new AmCharts.CategoryAxesSettings();
chart.categoryAxesSettings.equalSpacing = true;
//makeChart version
AmCharts.makeChart("chartdiv", {
// ...
"categoryAxesSettings": {
"equalSpacing": true
},
// ...
});
Demo

How to assign javascript variable to amcharts dataloader?

I need to assign a javascript variable to amcharts dataloader. but following code does not work (Graph does not draw)
AmCharts.ready(function () {
var data = [{"employee_no": "101","Salary": "1000"},{"employee_no": "102","Salary": "1500"},{"employee_no": "103","Salary": "1100"},{"employee_no": "104","Salary": "1900"},{"employee_no": "105","Salary": "1200"},
{"employee_no": "106","Salary": "1800"},{"employee_no": "107","Salary": "2000"},{"employee_no": "108","Salary": "1500"}];
var chart = new AmCharts.AmSerialChart();
chart.dataLoader = data;
chart.categoryField = "employee_no";
var graph = new AmCharts.AmGraph();
graph.valueField = "Salary";
graph.type = "line";
graph.bullet = "round";
graph.lineColor = "#8d1cc6";
chart.addGraph(graph);
chart.write('chartdiv');
});
but if I use below code it works fine.
chart.dataLoader = {
url: "MY_URL",
postProcess: function (data, options) {
if (data === null) {
data = [];
options.chart.addLabel("50%", "50%", "No Data Available");
}
return data;
}
};
What is the error of above code ? I cannot figure it out.
Thanks you
Thank you martynasma, You are right
I have to use chart.dataProvider instead of chart.dataLoader
That solved my problem. We have to use chart.dataLoader only with http request.

Categories