Cannot set property 'values' of undefined - javascript

I'm using zingchart gauges in my code. My problem is that I can't change the gauge value dynamically.
I'm getting this error:
Cannot set property 'values' of undefined
I'm using flask API. How can I change this variable value with flask API? Do you have any idea what can I use for dynamic gauge?
function fetchData() {
$.ajax({
url: "api/read",
method: "GET",
success: function(data, status, xhr) {
//var array = data.split(",").map(Number);
a = JSON.parse(data);
$('#myChart').series.values = 20;
//console.log(a);
},
error: function(xhr, status, error) {
$("#dataHeader").html("Error: \n" + error);
}
});
}
var myConfig4 = {
"type": "gauge",
"scale-r": {
"aperture": 200,
"values": "0:100:10",
"center": { //Pivot Point
"size": 6,
"background-color": "#66CCFF #FFCCFF",
"border-color": "#000000"
}
},
"plot": {
"csize": "5%",
"size": "85%",
"background-color": "#000000"
},
"series": [{
"values": [] // i need to change this value
}]
};
zingchart.render({
id: 'myChart',
data: myConfig4,
height: "75%",
width: "75%"
});
setInterval(fetchData, 1000);

you can use setseriesvalues and use array as value.
success: function(data, status, xhr) {
a = JSON.parse(data);
zingchart.exec('myChart', 'setseriesvalues', {
plotindex: 0,
'values': [20]
});
//console.log(a);
}

Related

How to bind JSON data from ajax call to DataSource of pivot table webdatarocks

Here the data is not binding in the following code:
var pivot = new WebDataRocks({
container: "#wdr-component",
toolbar: true,
height: 395,
report: {
dataSource: {
dataSourceType: "json",
data: getData()
},
"slice": {
"rows": [
{
"uniqueName": "RLI_RAV_GRP_DES"
}
],
"columns": [
{
"uniqueName": "LEVEL1"
},
{
"uniqueName": "LEVEL2"
}
],
"measures": [
{
"uniqueName": "Q1",
"aggregation": "sum"
},
{
"uniqueName": "Q2",
"aggregation": "sum"
},
{
"uniqueName": "Q3",
"aggregation": "sum"
},
{
"uniqueName": "Q4",
"aggregation": "sum"
}
]
},
options:
{
grid: {
title: "Sales Report"
}
}
}
});
function getData() {
$.ajax({
type: "GET",
url: "NACGSample.aspx/GetPivotReportList",
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (msg) {
return JSON.parse(msg.d);
//return msg.d;
},
error: function (msg) { return alert(msg); }
});
}
The issue is that you can not return a value from an asynchronous call (AJAX request).
The solution is to call a function inside your success: callback that passes the data when it is available.
Please check the following CodePen: https://codepen.io/webdatarocks/pen/eYErgGL?editors=1010

Vue.JS, Axios, CanvasJS - get data from API and populate / render a chart

I am new to Vue.JS and trying to have reactive data in my chart, one step at a time. This is my Javascript:
window.onload = function () {
var chartParent = new Vue({
el: '#chartContainer',
data: function() {
return {
chart: null,
tempData: null
}
},
computed: {
chartOptions() {
return {
theme: "light2",
subtitles: [
{
text: "Performance",
fontStyle: "bold",
verticalAlign: "center",
dockInsidePlotArea: true
},
{
text: "Legend (On Hover)",
fontStyle: "bold",
verticalAlign: "bottom",
horizontalAlign: "right",
dockInsidePlotArea: true
}
],
toolTip:{
enabled: false,
},
data: [
{
type: "doughnut",
indexLabel: "",
mousemove: this.donutChartMousemove,
showInLegend: false,
dataPoints: [
{
"y": 90,
"label": "Temp In Range",
"color": "#218340",
"legendLabel": "(Temp ≤ + 1°F)"
},
{
"y": 5,
"label": "Temp In Tolerance",
"color": "#F7B731",
"legendLabel": "(+ 1°F < Temp <= 2°F)"
},
{
"y": 5,
"label": "Temp Above Setpoint",
"color": "#A62337",
"legendLabel": "(Temp > + 2°F)"
}
]
}
]
}
}
},
mounted: function () {
axios
.get('/api/temps')
.then((response) => { this.tempData = response.data })
.catch((error) => { console.log(error) })
this.chart = new CanvasJS.Chart("chartContainer", this.chartOptions);
this.chart.render();
},
methods: {
donutChartMousemove: function(e){
this.chart.subtitles[0].set("text", e.dataPoint.label + " (" + e.dataPoint.y + "%)");
this.chart.subtitles[0].set("fontColor", e.dataPoint.color);
this.chart.subtitles[1].set("text", e.dataPoint.legendLabel);
this.chart.subtitles[1].set("fontColor", e.dataPoint.color);
}
}
})
}
This is the JSON data at /api/temps:
{
"Temps_agg": {
"Avg_Dry_Bulb": 95,
"Station1": {
"TempInRange_Day": 92.7777777777778,
"TempInTolerance_Day": 7.2222222222222,
"TempAboveSetpoint_Day": 0
},
"Station2": {
"TempInRange_Day": 83.22222222222227,
"TempInTolerance_Day": 16.777777777777832,
"TempAboveSetpoint_Day": 0
}
}
}
I want to pass the values in Station1 to my chart like so (code segment from above):
dataPoints: [
{
"y": this.tempData.Temps_agg.Station1.TempInRange_Day,
"label": "Temp In Range",
"color": "#218340",
"legendLabel": "(Temp ≤ + 1°F)"
},
{
"y": this.tempData.Temps_agg.Station1.TempInTol_Day,
"label": "Temp In Tolerance",
"color": "#F7B731",
"legendLabel": "(+ 1°F < Temp <= 2°F)"
},
{
"y": this.tempData.Temps_agg.Station1.TempAboveSetpoint_Day,
"label": "Temp Above Setpoint",
"color": "#A62337",
"legendLabel": "(Temp > + 2°F)"
}
]
When I do that, I get this error:
app.js:28150 [Vue warn]: Error in mounted hook: "TypeError: Cannot read property 'Temps_agg' of null"
//trim
app.js:29413 TypeError: Cannot read property 'Temps_agg' of null
//trim
If I print the axios response, I can see the JSON response in the console:
axios
.get('/api/temps')
.then((response) => { console.log(response.data) })
.catch((error) => { console.log(error) })
I suspect I'm causing a "race" condition?
Edit 1: Thank you #hmm for the direction. This is what worked for me:
async created () {
try {
let response = await axios.get('/api/temps');
this.chartData = response;
this.chart = new CanvasJS.Chart("chartContainer", this.chartOptions);
this.chart.render();
}catch(err){
console.log(err);
}
},
You'll notice I removed mounted () and I now render the chart in async created ().
The solution from Edit 1 is a bit "hacky" in the sense that Vue will not wait for promises to resolve before continuing the component lifecycle. It may work, but it doesn't seem like Vue way to do things.
I don't know your use case, but it seems like you can keep this very simple.
data () {
return {
chart: null
}
},
mounted () {
axios.get('/api/temps')
.then((response) => {
let chartOptions = {
...
data: response.data,
...
}
this.chart = new CanvasJS.Chart("chartContainer", chartOptions);
this.chart.render();
})
.catch((error) => { console.log(error) })
}

jQuery UI autocomplete in AJAX/JSON

I have a problem with jQuery UI autocomplete that I'm trying to resolve with a lot of research and only resolved it partialy. I've managed to make it work at all with this code:
$("#term").autocomplete({
source: function (request, response) {
$.ajax({
url: "https://wger.de/api/v2/exercise/?format=json",
type: "GET",
data: { name: request.term },
dataType: "json",
success: function(data) {
response($.map(data, function(item) {
return {
label: item,
value: item
}
}));
}
});
}
});
I'm working with open source API in JSON, here is an example:
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": 436,
"license_author": "Andrew Carothers",
"status": "1",
"description": "<p>1 Minute for each exercise</p>\n<ol>\n<li>Hold feet 6 inches off ground</li>\n<li>Crunches</li>\n<li>Side Crunches (L)</li>\n<li>Side Crunches (R)</li>\n<li>Heel Touches</li>\n<li>Plank Crunch</li>\n<li>Scissor Kicks</li>\n<li>Swim Kicks</li>\n<li>V Crunches</li>\n<li>Hold feet 6 in off ground</li>\n</ol>\n<p>Exercises can be substituted to vary workout</p>",
"name": "10 Min Abs",
"name_original": "10 Min Abs",
"creation_date": "2016-12-09",
"uuid": "3c5f6e1c-cb22-4a9f-a13e-d14afeb29175",
"license": 2,
"category": 10,
"language": 2,
"muscles": [],
"muscles_secondary": [],
"equipment": []
}
]
}
I want to get autocomplete suggestions with letters from "name" in JSON, but instead I've got whole JSON array, even with non-existing objects. I've already tried item.results[0].name, but everything I've got is TypeError: item.results is undefined. How to modify $.ajax to get "name" value of JSON object in autocomplete suggestions?
Thanks for any help.
does this work :
$("#term").autocomplete({
source: function (request, response) {
$.ajax({
url: "https://wger.de/api/v2/exercise/?format=json",
type: "GET",
data: { name: request.term },
dataType: "json",
success: function(data) {
response($.map(data.results, function(index,item) {
return {
label: item.name,
value: item.name
}
}));
}
});
}
});

dataTables Change Data for ajax call

I'm using the following function to load a DataTables table with data from the server. I would like to reload the table with different parameters on a click event only i cant work out how to do this. If i call reload it just reloads with the original parameters if i reinitialise the whole table it throws an error as the table already exists.
I have been looking into fnServerParams but cant work out if it would help or not.
If anyone can point me in the correct direction that would be great.
function LoadRiskProfileModalTable(userId, teamId, riskProfileClass) {
var params = {
userId: userId,
teamId: teamId,
riskProfileClass: riskProfileClass
};
var data = JSON.stringify(params);
//if (!$.fn.DataTable.isDataTable("#riskProfileTable")) {
var table = $("#riskProfileTable").DataTable({
"bProcessing": true,
"sAjaxSource": "WFMHome.aspx/GetRiskProfileDrillThroughDatatable",
"fnServerData": function (sSource, aoData, fnCallback) {
//aoData.push(JSON.stringify(params));
$.ajax({
"dataType": 'json',
"contentType": "application/json; charset=utf-8",
"type": "POST",
"url": sSource,
"data": data,
"success": function (msg) {
var json = jQuery.parseJSON(msg.d);
fnCallback(json);
$("#riskProfileTable").show("fast", function () { $('#riskProfileTableLoading').hide("fast") });
},
error: function (xhr, textStatus, error) {
if (typeof console == "object") {
appendAlert("errorAlertPlaceholder", xhr.responseText, 1, "danger");
console.log(xhr.status + "," + xhr.responseText + "," + textStatus + "," + error);
}
}
});
},
"columns": [
{ "data": "CaseHandler" },
{ "data": "caseAreaText" },
{ "data": "RiskProfileText" },
{ "data": "PassChecks" },
{ "data": "F1Checks" },
{ "data": "F2Checks" },
{ "data": "F3Checks" },
{ "data": "CurrentChecks" }
]
});
//}
//else {
// $('#riskProfileTable').DataTable().ajax.reload();
// }
};
If you just want to replace the data you have now by the data coming from the server, try to replace the success method by:
"success": function (msg) {
var json = jQuery.parseJSON(msg.d); //I assume it's the data set
var table = $("#riskProfileTable").DataTable();
table.rows.clear(); //clear the current data
table.rows.add(json).draw();
$("#riskProfileTable").show("fast", function () { $('#riskProfileTableLoading').hide("fast") });
},

passing json array to ajax call in Javascript

guys i know its dummy questions but i spent hours on this and cant reach .. I am trying to pass a JSON array to JSP via an AJAX call in another JS file. It is giving me a 404 error. Any help would be appreciated. Here is my code:
function GridLibrary(fileName) {
this.fileName = fileName;
}
GridLibrary.prototype = {
setFileName : function(fileName) {
this.fileName = fileName;
},
getFileName : function() {
return this.fileName;
}
};
GridLibrary.prototype.display = function() {
$.ajax({
url : this.getFileName(),
dataType: "json",
error : function(that, e) {
console.log(e);
},
success : function(data) {
alert("found");
}
});
};
var Json = [{
"id": 1,
"name": "name1",
"age" : 10,
"feedback": "feedback1"
}, {
"id": 2,
"name": "name2",
"age" : 90,
"feedback": "feedback2"
}, {
"id": 3,
"name": "name3",
"age" : 30,
"feedback": "feedback3"
}, {
"id": 4,
"name": "name4",
"age" : 50,
"feedback": "feedback4"
}];
new GridLibrary(Json).display();
You need to have a valid url to send the values to the backend:
function GridLibrary(url, data) {
this.url = url;
this.data = data;
}
GridLibrary.prototype = {
setData: function(data) {
this.data = data;
},
getData: function() {
return this.data;
},
setUrl:function(url){ this.url = url; },
getUrl:function(){ return this.url; },
display : function() {
$.ajax({
url: this.getUrl, // <----the url where you want to send the data
data:this.getData, //<----should be the array data
dataType: "json",
contentType:"application/json", // <----add this contentType
error: function(that, e) {
console.log(e);
},
success: function(data) {
alert("found");
}
});
}
};
var url = '/url/to/send',
data = [{}....];
new GridLibrary(url, data).display();

Categories