Chart.js - Ajax response not accept - javascript

chart.js not accept ajax post - json respose.i couldn't solve it yet.please help..
https://prnt.sc/spt4p3
https://prnt.sc/spt6j0
my json file is:
[{"DAYS":"01.05.2020","VALUES":"0"},{"DAYS":"02.05.2020","VALUES":"0"},{"DAYS":"03.05.2020","VALUES":"0"},{"DAYS":"04.05.2020","VALUES":"0"},{"DAYS":"05.05.2020","VALUES":"0"},{"DAYS":"06.05.2020","VALUES":"0"},]
javascript file is:
var days = [];
var values=[];
$.ajax({
url: 'class/report/daily_report.php',
type: 'POST',
data: {'reload': 'renew', 'type': 'rep_1'},
success: function (response) {
var jsonARR =$.parseJSON(response);
var k=0;
for ( var key in jsonARR ) {
days[k]=jsonARR[key]["DAYS"];
values[k]=parseInt(jsonARR[key]["VALUES"]);
k++;
}
}
});
var a = {
labels: days,
datasets: [{
backgroundColor: KTApp.getStateColor("danger"),
data: values
}]
};

Please remind that $.ajax() makes an asynchronous HTTP request. In you code however, you create the chart even before ans answer from that request is received.
The problem can be solved by moving the code responsible for chart creation inside the $.ajax() block as shown below.
$.ajax({
success: function(response) {
var jsonARR = $.parseJSON(response);
var k = 0;
for (var key in jsonARR) {
days[k] = jsonARR[key]["DAYS"];
values[k] = parseInt(jsonARR[key]["VALUES"]);
k++;
};
var a = {
labels: days,
datasets: [{
backgroundColor: KTApp.getStateColor("danger"),
data: values
}]
};
new Chart(...);
});

Related

Defining function without calling it immediately without events (on click/hover...)

I have a really huge jquery function, and to make it easier to read, I'd like to know how can I put it somewhere else and call it only inside another function (to be more specific, inside an ajax call, where I have it defined right now).
The problem is that when I define the function, it runs automatically, and I don't want that. I want it to run inside the ajax call, but not define it there.
Here's a sample code of what I have:
$.ajax({
type: 'post',
url: 'api/'+$("#id").val()+"/"+$("#from").val()+"/"+$("#to").val(),
data: {},
success: function generateChart(data) {
var results = JSON.parse(data);
if (results.error == true) {
var errCode = results.code;
alert(errCode);
}
else {
var chartjsTemp = [];
var chartjsDate = [];
for (var i = 0; i < results.length; i++) {
chartjsTemp.push(results[i].probeTemp);
chartjsDate.push(results[i].dateProbe);
}
var ctx = document.getElementById('myChart').getContext('2d');
var button = $("#submitButton");
submitButton.addEventListener("click", function(){
myChart.destroy();
});
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: chartjsDate,
datasets: [{
label: 'temp',
data: chartjsTemp,
backgroundColor: "rgba(240,240,240,0.5)"
}]
}
});
}
}
});
I want to put my "generateChart" function somewhere else. If I put it "somewhere else" and do just "success: generateChart()" it won't work, and instead run when the page loads.
You should call an external function, like this:
function extFunc(data){
...
}
$.ajax({
type: 'post',
url: 'xxx',
data: {},
success: function generateChart(data) {
extFunc(data);
}
});
You should be able to save all your functions in variables without actually calling them.
Here's an example:
var myFunc = function(param1) {
console.log(param1);
}
$(function() {
myFunc('test');
myFunc('test2');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Edit:
With your code sample it's basically the same.
Just define the success function outside and then call it on success.
If you success: generateChart(data) you could also try:
success: function(data) { generateChart(data); }.
Just move the definition outside an ajax call:
function generateChart(data) {
var results = JSON.parse(data);
if (results.error == true) {
var errCode = results.code;
alert(errCode);
} else {
var chartjsTemp = [];
var chartjsDate = [];
for (var i = 0; i < results.length; i++) {
chartjsTemp.push(results[i].probeTemp);
chartjsDate.push(results[i].dateProbe);
}
var ctx = document.getElementById('myChart').getContext('2d');
var button = $("#submitButton");
submitButton.addEventListener("click", function(){
myChart.destroy();
});
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: chartjsDate,
datasets: [{
label: 'temp',
data: chartjsTemp,
backgroundColor: "rgba(240,240,240,0.5)"
}]
}
});
}
}
$.ajax({
type: 'post',
url: 'api/'+$("#id").val()+"/"+$("#from").val()+"/"+$("#to").val(),
data: {},
success: function(data) {
generateChart(data);
}
});

How to push data to create pie chart - chart js

I have data from SQL in json code file (checked in Fiddler)
{"d":[{"__type":"Dashboards.Employee","name":"Test
Hen","turnover":"1500000,0000","color":"#231F20"},{"__type":"Dashboards.Employee","name":"Test
Bai","turnover":"130000,0000","color":"#FFC200"}]}
but i dont know, how to push them correctly in order to create pie chart
my ajax/javascript is here:
$.ajax({
url: 'HelloService.asmx/GetEmployeeDetail',
contentType: 'application/json;charset=utf-8',
data: JSON.stringify({ month: number }),
dataType: 'json',
method: 'post',
success: OnSuccess_,
error: OnErrorCall_
});
function OnSuccess_(response) {
var aData = response.d;
var arr = [];
//var ctx = document.getElementById('pele').getContext('2d');
$.each(aData, function (inx, val) {
var obj = {};
obj.label = val.name;
obj.value = val.turnover;
obj.color = val.color;
arr.push(obj);
});
var ctx = $("#pele").get(0).getContext("2d");
var myPieChart = new Chart(ctx).Pie(arr);}
function OnErrorCall_(response) {
console.log(error);
}
});
});
Am I missing something?
If i use static values (value, label, color) pie chart works without problem.
Thank you
I created the following FiddleJS for you: https://jsfiddle.net/cukyrh5h/1/
You need to replace the URL of the Ajax call with yours of course. You had some wrong syntax (too much braches in the end of your Snippet) and the API you were using was not working with ChartJS 2.4 anymore.
The code looks like the following:
$.ajax({
url:"/echo/json/",
data:data,
type:"POST",
success:OnSuccess_
});
function OnSuccess_(response) {
var aData = response.d;
var data = {
labels: [],
datasets: [{
data: [],
backgroundColor: []
}]
};
$.each(aData, function (inx, val) {
data.labels.push(val.name);
data.datasets[0].data.push(val.turnover);
data.datasets[0].backgroundColor.push(val.color);
});
var ctx = $("#pele").get(0).getContext("2d");
var myPieChart = new Chart(ctx, {
type: 'pie',
data: data
});
}
function OnErrorCall_(response) {
console.log(error);
}
Ok, i found problem, why i cant see my Chart. Maybe it will be useful for another members. Data in Database (turnover was daclared as money, i changed it to int .... and it works)

Pie chart crashes when no data from JSON

I am a beginner and learning web development. In my sample project I have created Pie Chart using ChartJS. I am getting data from REST Service. Everything is working fine and pie chart is getting rendered properly. The problem is when there is null data from REST then I am getting error in Chart.js.
Error:
JSON DATA FROM REST:
My sample project uses BackboneJS. I know the error is because there is no data coming from REST. How can I handle that so that m Pie Chart does not crash.
Below is the MODEL:
define(['backbone'], function(Backbone) {
var chart = Backbone.Model.extend({
urlRoot: 'SAMPLE REST URL',
defaults: function() {
return {
currMonthOccAvailVac: [],
};
},
fetch: function(data) {
var d = $.Deferred();
var self = this;
var ajaxRequest = $.ajax({
url: this.urlRoot,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(data)
});
ajaxRequest.done(function(json) {
var graphVar = {
currMonthOccAvailVac: [],
}
var yearSelected = (localStorage.getItem('date')).split("-")[0];
var monthSelected = (localStorage.getItem('date')).split("-")[1];
for (var i = 0; i < json.length; i++) {
var monthYear = json[i].columnstrDate.split("/");
var year = monthYear[0];
var month = monthYear[1];
if(month.length == 1)
if(month == (monthSelected - 1) && year == yearSelected)
{
graphVar.currMonthOccAvailVac.push(json[i].columndecOccPercentage);
graphVar.currMonthOccAvailVac.push(json[i].columndecVacantUnitsPercentage);
graphVar.currMonthOccAvailVac.push(json[i].columndecUnavailableUnitsPercentage);
}
}
self.set({
currMonthOccAvailVac: graphVar.currMonthOccAvailVac,
});
d.resolve();
});
//failure callback for ajax request.
ajaxRequest.fail(function(jqXHR, status) {
// Handle fail request
d.reject();
});
return d.promise();
}
});
// returning the model
return {
chart: chart
};
});
Place in ChartJS where actually code is breaking:
So how can I make sure even if graphvar.currMonthOccAvailVac has no value the pie chart does not crash. Kindly guide me.
EDIT
Currently in my View Model I did something like below. But I am not sure if this the right way to handle.
define(['backbone'], function(Backbone) {
var sixthSubViewModel = Backbone.View.extend({
template: _.template($('#myChart6-template').html()),
render: function() {
$(this.el).html(this.template());
var ctx = this.$el.find('#pieChart')[0];
var data = {
datasets: [{
data: this.model.attributes.currMonthOccAvailVac,
label: 'My dataset' // for legend
}],
labels: [
"Rented",
"Vacant",
"Unavailable",
]
};
// I AM CHECKING HERE THE LENGTH AND THE RNEDERING THE PIE CHART
if (this.model.attributes.currMonthOccAvailVac.length > 1)
var pieChart = new Chart(ctx, {
type: 'pie',
data: data,
otpions: {
legend: false
}
});
WHAT SHALL I PUT IN THE ELSE PART
},
initialize: function() {
this.render();
}
});
return sixthSubViewModel;
});

Creating multidimensional array inside each

I want to create a multidimensional array from the values I retrieved on an ajax post request.
API response
[{"id":"35","name":"IAMA","code":"24"},{"id":"23","name":"IAMB","code":"08"}]
jQuery code
var mulArr = [];
$.ajax({
type: 'POST',
url: '/path/to/APIendpoint',
dataType: 'json',
data: {
codes: codes
},
success: function(data) {
$.each(data, function(key, value) {
mulArr[key]['id'] = value.code;
mulArr[key]['text'] = value.name;
});
}
});
Syntax error
TypeError: mulArr[key] is undefined
I can properly fetch the data from the endpoint, the only error I encounter is the one I stated above. In perspective, all I want to do is simply a multidimensional array/object like this:
mulArr[0]['id'] = '24';
mulArr[0]['text'] = 'IAMA';
mulArr[1]['id'] = '08';
mulArr[1]['text'] = 'IAMB';
or
[Object { id="24", text="IAMA"}, Object { id="08", text="IAMB"}]
It happens because mulArr[0] is not an object, and mulArr[0]['id'] will throw that error. Try this:
var mulArr = [];
$.ajax({
type: 'POST',
url: '/path/to/APIendpoint',
dataType: 'json',
data: {
codes: codes
},
success: function(data) {
$.each(data, function(key, value) {
mulArr.push({id: parseInt(value.code), text: value.name});
// or try this if select2 requires id to be continuous
// mulArr.push({id: key, text: value.name});
});
}
});
Alternative to using push (which is a cleaner approach) is to define the new object.
mulArr[key] = {
id: value.code,
text:value.name
};
Another way of achieving what you want would be this one:
var mulArr = [];
$.ajax({
type: 'POST',
url: '/path/to/APIendpoint',
dataType: 'json',
data: {
codes: codes
},
success: function(data) {
mulArr = data.map(value => ({ id: parseInt(value.code), text: value.name }));
}
});
This is cleaner and also uses builtin map instead of jQuery $.each. This way you also learn the benefits of using the map function (which returns a new array) and also learn useful features of ES2015.
If you cannot use ES6 (ES2015) here is another version:
mulArr = data.map(function (value) {
return {
id: parseInt(value.code),
text: value.name
};
});
I guess you can already see the advantages.

2d array in javascript post to the server via ajax

I have got a 2d array in javascript.
var erg = new Array();
for (var i in val) {
erg[i] = new Array();
for (var j in val[i]()) {
erg[i][j] = val[i]()[j]();
}
}
but when i wanted to post it to the server only the 1d array gets passed. (erg[i])
$.ajax({
url: '/Document/UpdateTableValues',
type: 'POST',
data: {
docid: documentId,
page: self.CurrentPage(),
elementid: element.Values()[1](),
text: erg
},
success: function (data) {
self.SaveState("Dokument gesichert");
}
});
how can i send the whole array to the server?
thanks
There is just one mistake : use text: erg +"" instead of text: erg.

Categories

Resources