Assign array of strings from JSON to Handsontables object in javascript? - json

I am trying to assign array of string to handsontables column as auto-complete. I am getting this JSON data from AJAX calls.
I am not getting to assign to source:. Please follow the code.
var loadBU = function(data) {
$.ajax({
url: "/EditInitiatives.svc/GetBUData",
data: "clientId=" + $value.val(),
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
data(res);
},
error: function (error) {
alert("Error: " + error.responseText);
}
});
};
$("#example2").handsontable({
data: getCarData(),
startRows: 7,
startCols: 4,
columns: [
{ data:'BusinessUnit',
type:'autocomplete',
source:loadBU(function(output){
var results = output.d
var arr = [], item;
for (var i = 0, len = results.length; i < len; i++) {
item = results[i];
arr.push([[item]]);
}
return arr;
}),
strict: true
},
]
});
It suppose to be like that EX: source: ["yellow", "red", "orange", "green", "blue", "gray", "black", "white"],
I don't understand how to assign array to source.
Reference

Your "return arr;" does not return to the "source:", it returns to the "loadBU" function.
For example, you could do:
success: function (res) {
var arr = data(res);
},
This is why it is not being assigned.
Try making your Ajax call before $("#example2").handsontable({ and save it to someVariable, then set the source: someVariable
Depending on what your Ajax call returns, you may also need to make some manipulations. For example, I needed to loop through and load into an array:
function AppendToArray(ajaxValues, theArray) {
for (var i = 0; i < ajaxValues.length; i++) {
theArray.push('' + ajaxValues[i].Text + '');
}
}
I hope this helps

I use it like this:
var workers = null;
$.ajax({
url: siteUrl + "/Worker/Get",
dataType: 'json',
type: 'GET',
cache: false
})
.done(function (data) {
$("#worker-grid").handsontable({
data: data,
rowHeaders: true,
colHeaders: ["internal<BR />identification", "name", "mobile", "e-mail address", "national<BR />identification", "partner", "source"],
colWidths: [100, 150, 100, 250, 150, 150, 100],
columns: [
{ data: "intId" },
{ data: "name" },
{ data: "mobile" },
{ data: "mail" },
{ data: "extId" },
{
data: "partner", type: 'dropdown', source: function (query, process) {
$.ajax({
url: siteUrl + "/Partner/Get",
dataType: 'json',
type: 'GET',
cache: false
})
.done(function (data) {
var values = [];
for (i in data) values.push(data[i].name);
process(values);
});
}
},
{ data: "source" }
],
columnSorting: true,
minSpareRows: 1
});
workers = $("#worker-grid").data("handsontable");
});
The key in assigning to the source is the process parameter in the source function.
I would like to add however that this approach will be fetching data from the server with every use. My example above uses a dropdown which does not make sense.. But it's the correct approach when using with autocompletion.

Related

Update Chart.js data with ajax

I want to update my chart with ajax and Flask but
I can not update the data:
var chart = new Chart(canvas, {
type: "line",
datasets: [{
label: 'My Dataset',
}]
})
$(document).ready(function () {
$.ajax({
dataType: "text",
contentType: "application/json",
url: '{{ url_for("data_page") }}',
type: "post",
data: JSON.stringify({
timeDelta: "7",
technologie: "Java",
}),
success: function (data) {
let json = $.parseJSON(data); ==> [["2021-06-04", "2021-06-05"],[47, 3]]
chart.data.labels.push(json[0]); ==> It seems to work
chart.data.datasets[0].data = json[1]; ==> here I get : "Cannot set property 'data' of undefined"
chart.update();
}
});
});
I don't understand ,
where am I wrong ?
Thanks for any help !
It doesn't work because you initially create the chart with wrong configuration. The labels and datasets arrays must be contained in a data object.
Try this instead:
var chart = new Chart(canvas, {
type: 'line',
data: {
labels: [],
datasets: [{
label: 'My Dataset',
data: []
}]
}
});

How do I create a Hierarchical Pie chart in html and servlet or jsp?

I want to create a Hierarchical Pie chart that displays percentages? How do I create a Hierarchical Pie chart using d3 in Java?
It should look like this: http://yhnavein.github.io/d3-hierarchical-pie/
Please provide me code to create using jsp, ajax, json and servlet.
if ($('#Start_date').val().length==0 ) {
alert("Please Select Start Date");
}else if($('#end_date').val().length==0){
alert("Please Select End Date");
}
else{
$('#chart-container-OTAType').text();
var graphData;
var data = {
action: "getOTATypeByDate",
fromDate: fromDate,
toDate: toDate
};
var dataString = 'MainJson=' + JSON.stringify(data);
$.ajax({
type: 'POST',
url: './OTAServlet',
data: dataString,
dataType: 'text',
async: false,
success: function (result) {
var responseData = $.trim(result);
graphData = JSON.parse(responseData);
if (FusionCharts('OTAType-Pie-chart')) {
FusionCharts('OTAType-Pie-chart').dispose();
}
$("#divOTATypeGraph").text('');
var chart = new FusionCharts({
type: 'pie2d',
renderAt: 'divOTATypeGraph',
id: 'OTAType-Pie-chart',
width: '650',
height: '500',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Report for OTA",
"showvalues": "1",
"showpercentvalues": "1",
"showpercentintooltip": "0",
"bgcolor": "#FFFFFF",
"basefontcolor": "#400D1B",
"showshadow": "0",
"animation": "0",
"showborder": "0",
"paletteColors": '#9B609B,#AACB47,#1A9494,#BE6F71, #AACB47',
},
"data": graphData
},
"events": {
"dataPlotClick": function (eventObj, dataObj) {
var text = dataObj.categoryLabel;
if(text == 'OTA') {
otaStatus = 1;
}
if (otaStatus > 0) {
getBrandStatusByDate(otaStatus);
}
}
}
});
chart.render();
}

How to send array with json using ajax

How do I send an array with json using ajax? I want to store email and name:
$.ajax({
url: 'index.php?route=module/newsletters/news',
type: 'post',
data: 'email=' + $('#txtemail').val() ,
dataType: 'json',
success: function(json) {
alert(json.message);
}
});
Let's suppose you have an array?
var array = [
"student1" : {
"name": "jon",
"email": "test#example.com"
},
"student2" : {
"name": "jon2",
"email": "test2#example.com"
}
]
$.post('index.php?route=module/newsletters/news', {
data : JSON.stringify(array),
datatype : 'application/json',
}, function(success) {
console.log(success)
});
Your question is not clear.please write your question in correct format.then community can be resolve your question easily.
I assume your problem and give solution for that.
var array = {name:'dua',email:'dua#gmail.com'};
$.post('index.php?route=module/newsletters/news', {
data : JSON.stringify(array)
}, function(success) {
console.log(success)
});
var postData = { "email":email,"name":name }
$.ajax({
url: 'index.php?route=module/newsletters/news',
type: 'post',
data: postData,
dataType: 'json',
success: function(json) {
alert(json.message);
}
});

How to send array of objects to a controller method?

I need your help, I have this piece of code in the controller side
public bool DraftMessage(message[] draftMessages, HttpPostedFileBase[] files = null)
{
return true;
}
and I use this client side code to send the data
function DraftMessage()
{
var myArray = [{ 'To': [1, 2], "Title": "Hello" }, { 'To': [1, 2], "Title": "Hello" }]
$.ajax({
type: "POST",
url: "#Url.Action("DraftMessage","Activities")",
datatype: "json",
traditional: true,
data: JSON.stringify({ draftMessages: myArray }),
beforeSend: function () { }
}).done(function (data) {});
}
$("input, select, textarea").change(function () { DraftMessage(); });
var contents = $('.note-editable').html();
$(".compose-message").on("blur", ".note-editable", function () {
if (contents != $(this).html()) {
DraftMessage();
contents = $(this).html();
}
});
but when I debug it I found that the array of messages in the controller is null so could anyone guide me about what I did wrong and help me to fix this issue.
You need to set contentType as "application/json"
function DraftMessage() {
var myArray = [{ 'To': [1, 2], "Title": "Hello" }, { 'To': [1, 2], "Title": "Hello" }];
$.ajax({
type: "POST",
url: "#Url.Action("DraftMessage","Home")",
contentType: "application/json",
data: JSON.stringify({ draftMessages: myArray })
}).done(function (data) {
console.log(data);
});
}
The default value of contentType header is "application/x-www-form-urlencoded" . Since we are sending the json stringified version of a a complex data structure, we should explicitly specify the contentType

Get current day values from database to plot on highcharts

Hello i am designing a webserver which shows me a power consumption graph from a mysql database. I am a beginner and have written a code with some help that uses ajax calls to fetch the data from the database and plot it on the highcharts. Problem is that I get all the historic values saved in my database but I want only the values of current day to be plotted on the chart. This is my js code:
Highcharts.setOptions({
global: {
useUTC: false
}
});
$('#container').highcharts({
chart: {
type: 'area',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
},
title: {
text: ''
},
xAxis: {
type: 'datetime',
tickPixelInterval: 100
},
yAxis: {
title: {
text: 'POWER'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%d-%m-%Y %H:%M:%S', this.x) + '<br/>' +
Highcharts.numberFormat(this.y);
}
},
legend: {
enabled: true
},
exporting: {
enabled: false
},
series: [{
name: 'Power Consumption',
data: (function () {
var data = [], i, t, d;
var request = {};
request['EndPoint'] = "arduino/charts/analog/fetch";
$.ajax({
type: "POST",
url: "../Server/fyp-processor.php",
data: JSON.stringify(request),
dataType: "json",
async: false,
success: function (result) {
if(result.Code == "1008" && (result.Data != null || result.Data != undefined)) {
for(i = 0; i < result.Data.Historic.length; i++) {
t = result.Data.Historic[i].DateTime.split(/[- :]/);
d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
data.push({
x: d,
y: parseInt(result.Data.Historic[i].Value)
});
}
}
}
});
return data;
}())
}]
});
It calls a fyp-processor php script that contains this code:
else if($postData['EndPoint'] == 'arduino/charts/analog/fetch') {
#result set
$resultSet = null;
#get all historic analog chart data
$results = $db->charts();
if(count($results) > 0) {
foreach($results as $result) {
$resultSet['Historic'][] = $result;
}
}
I would be glad if anyone could help me out to get only current DAY's data and also what changes I can do to it then to get current month and current week's data too.