DataTables column data convert properly - javascript

this is what i look at
and this is what i received from server
function requestData() {
$.ajax({
url: "<c:url value='/abs/guide/guideSampleChartData1Ajax.do'/>",
type: "GET",
dataType: "json",
success: function(data) {
for(var i in data) {
chart.addSeries({
name: data[i].name,
data: data[i].data
});
}
console.log(data);
$("#table").dataTable({
"data": data,
"columns": [
{ "data": "name" },
{ "data": "categData" },
{ "data": "data"}
]
});
}
});
}
and this is my code, i want to my datatables looking accordingly
so, what part of code, i change??

Related

Row Not Updating

I am trying to update a row in a datatable using editable cells. It works to update on the interface but the data does not go into the api and after I reload the page the modification dissapear.
function buildlist() {
var url = 'http://127.0.0.1:8000/api/sarcini-list/';
fetch(url).then(
res => {
res.json().then(
data => {
console.log(data);
var table
const createdCell = function(cell) {
let original;
cell.setAttribute('contenteditable', true)
cell.setAttribute('spellcheck', false)
cell.addEventListener("focus", function(e) {
original = e.target.textContent
})
cell.addEventListener("blur", function(e) {
if (original !== e.target.textContent) {
const row = table.row(e.target.parentElement);
$.ajax({
type: "PUT",
url: 'http://127.0.0.1:8000/api/sarcini-detail/' + row.data().idSarcina,
data: row.data()
})
console.log('Row changed: ', row.data())
}
})
}
table = $('#datatable').DataTable({
columnDefs: [{
targets: '_all',
createdCell: createdCell
}],
scrollX: true,
data: data,
columns: [
{ data: 'idSarcina' },
{ data: 'nr_tren' },
{ data: 'nr_locomotiva' },
{ data: 'plecare' },
{ data: 'ora_plecare1' },
{ data: 'ora_sosire1' },
{ data: 'angajat1' },
{ data: 'angajat2' },
{ data: 'schimb1' },
{ data: 'ora_plecare2' },
{ data: 'ora_sosire2' },
{ data: 'angajat3' },
{ data: 'angajat4' },
{ data: 'schimb2' },
{ data: 'ora_plecare3' },
{ data: 'ora_sosire3' },
{ data: 'angajat5' },
{ data: 'angajat6' },
{ data: 'sosire' },
{ data: 'ora_plecare4' },
{ data: 'ora_sosire4' },
{ data: 'angajat7' },
{ data: 'angajat8' }
],
});
}
)
}
)
}
$(document).ready(function() {
buildlist();
});
I modified the field "NUMAR TREN" and as you can see in the console in the api the change does not take place but in the interface it looks ok.
This is how it looks in console and interface

C3 chart with JSON data

I am trying to populate a C3 chart with dynamic data from a SQL database. I have c# web method that when called by my javascript produces the following JSON string
[{"y":"5","item1":"Lion Wharf"},{"y":"31","item1":"Millbrook Park P2"},{"y":"84","item1":"Pinfield Meadows"}]
I'm using the following javascript on pageload but getting error "a.forEach is not a function"
$.ajax({
type: "POST",
url: "additions.aspx/GetPiechartData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "true",
cache: "false",
success: function (result) {
OnSuccess(result.d);
},
error: function (xhr, status, error) {
alert(error);
}
});
function OnSuccess(response) {
var abc = JSON.stringify(response);
window.location.replace(response);
var chart = c3.generate({
bindto: '#chart-var-project',
data: {
json: response,
keys: {
x: 'y',
value: ['item1']
},
type: 'donut'
},
donut: {
title: "Approval",
width: 40,
label: {
show: false
}
},
color: {
pattern: ["#ff9800", "#78c350", "#f7531f"]
}
});
I'm very new to Javascript and would really appreciate a pointer here
Thanks!
You have to format your json response to fit the expected format of C3 for Donut graph type.
function OnSuccess(response) {
var data = {};
var value = [];
JSON.parse(response).forEach(function(d) {
data[d.item1] = d.y;
value.push(d.item1);
});
c3.generate({
data: {
json: [data],
keys: {
value : value
},
type: 'donut'
},
donut: {
title: "Approval",
width: 40,
label: {
show: false
}
},
color: {
pattern: ["#ff9800", "#78c350", "#f7531f"]
}
})
}
Your server will normally output a string, so using a JSON.parse will transform this string into a json object.
function OnSuccess(response) {
var jsonData = response.d;
var chart = c3.generate({
bindto: '#chart-var-project',
data: {
json: JSON.parse(jsonData),
}
});
}

How to send Jquery datatable data to servlet?

I want to send Jquery datatable to servlet. below is the code.
Jquery in JSP
var table2 = $('#itemtable').DataTable( {
columns: [
{ data: "p_no"},
{ data: "p_date"},
{ data: "s_id"},
{ data: "it_id" },
{ data: "it_name" },
{ data: "it_type" },
{ data: "it_uni_price" },
{ data: "it_qty" },
{ data: "it_tot_price" }
],
order: [ 1, 'asc' ],
bProcessing: true,
bSort: true,
bJQueryUI: true,
bLengthChange: true,
bPaginationType: "two_button"
} );
Ajax request on Save button as below
var oTable = $("#table2").dataTable();
updateDatabase(oTable.fnGetData());
And the updateDatabase() as below
function updateDatabase(dataTable) {
$.ajax({
type: "POST",
url: "/ERP/Purchase",
cache: false,
dataType: "json",
data:{dataTable: dataTable},
success: function(html){
//success
}
});
}
How do I get my datatable data to my servlet?

Kendo datasource shema.data does not work for dropdownlist

I have Odata WebApi, and I want to populate my dropdownlist with data from there.
I have datasource:
var postsDataSource = new kendo.data.DataSource({
type: 'odata',
serverFiltering: true,
transport: {
read: {
url: "/odata/Posts",
dataType: "json"
},
},
schema: {
model: kendo.data.Model.define({
Id: "Id",
RegionId: "RegionId"
}),
data: function (res) {
debugger;//this code is inaccessible!
console.log(res);
return res.value;
}
},
});
and dropdownlist like this:
var posts = $("#searchPost").kendoDropDownList({
optionLabel: "Выберите регион...",
dataTextField: "NameRu",
dataValueField: "Id",
dataSource: postsDataSource,
}).data("kendoDropDownList");
This part of code executes odata query and return me the following json response in the firebug's console:
{
"odata.metadata":"http://localhost:11029/odata/$metadata#Posts","odata.count":"13","value":[
{
"Id":0,"Number":"Lenina45","RegionId":1,"NameRu":"\u041b\u0435\u043d\u0438\u043d\u0430 45","NameKz":"\u041b\u0435\u043d\u0438\u043d\u0430 45","ShortName":"\u041b\u0435\u043d\u0438\u043d\u0430 45","DateBegin":null,"DateEnd":null,"OptimisticLockField":null
},{
"Id":1,"Number":"Zhumabaeva15","RegionId":2,"NameRu":"\u0416\u0443\u043c\u0430\u0431\u0430\u0435\u0432\u0430 15","NameKz":"\u0416\u0443\u043c\u0430\u0431\u0430\u0435\u0432\u0430 15","ShortName":"\u0416\u0443\u043c\u0430\u0431\u0430\u0435\u0432\u0430 15","DateBegin":null,"DateEnd":null,"OptimisticLockField":null
},
.....
]
}
Right after this response I am getting the following strange error:
TypeError: d.d is undefined;
And dropdownlist doesn't show me above json response.
When I populated kendo grid with odata web api, the following code in datasource solved my problem:
schema: {
data: function (res) {
return res.value;
}
},
but now, when I use it for dropdownlist it doesn't work at all, it's inaccessible.
PS> Sorry for my bad English.
You Data Is on the inner object "value" on your response , your response consist on page size , metadata url so we need to prase the data that kendo dataSource can understand here is a exsample
: Note Remove "type: 'odata'" and check , since you are saying the dataSource where the Data is from the Data function no need of it as I think.
var postsDataSource = new kendo.data.DataSource({
serverFiltering: true,
transport: {
read: {
url: "/odata/Posts",
dataType: "json"
},
},
schema: {
model: {
Id: "Id",
fields: {
Id: { type: "number" },
NameRu: { type: "string" },
NameKz: { type: "string"},
ShortName: { type: "string" }
}
},
data: function (response) {
return response.value;
},
total: function(response) {
return response.odata.count;
}
},
});
try this hope this helps.

values not updated after an ajax response

I am sending some form data via ajax to a php script in the same page. PHP must process the data and show results in the same page.
I am using this syntax for ajax:
$.ajax
({
type: "POST",
url: "",
data: $("form").serialize(),
success: function(result)
{
updatechart();
console.log(result);
}
});
I am basically trying to update some values in a chart based on data entered in the form and after processed by a php script. I get the whole source of the page when I do console.log(result); and the values are updated in my console after doing this but the chart is not updated. When I view-source the page, the values remain the same. What should I do?
function updatechart() {
var json=<?php echo json_encode($GLOBALS['json']); ?>;
var direct=json['direct'];
var total=json['total'];
var referred=total-direct;
var aid=new Array();
var count=new Array();
for(var i=0;i<json['aid'].length;i++) {
aid[i]=json['aid'][i];
count[i]=json['count'][i];
}
var series = [{
name : "Referred",
data: [referred]
}, {
name: "Direct",
data: [direct]
}];
for(var i=0; i<aid.length;i++) {
series.push({
name: 'AID-'+[aid[i]],
data: [count[i]]
})
}
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'User Source Chart'
},
xAxis: {
categories: ['Users']
},
yAxis: {
min: 0,
title: {
text: 'Total users'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.percentage:.0f}%)<br/>',
shared: true
},
plotOptions: {
column: {
stacking: 'percent'
}
},
series: series
};
chart = new Highcharts.Chart(options);
}
This is my updatechart() code. The problem is, json value is not updated.
Pass the result as parameter to updatechart()
$.ajax
({
type: "POST",
url: "",
data: $("form").serialize(),
success: function(result)
{
updatechart(result);
}
});
then access the results via parameter.
function updatechart(result) {
//.......
//.......
console.log(result);
}
Hope you're trying something like this.
That is expected behavior. Move your PHP processing to a different page.
$.ajax
({
type: "POST",
url: "anotherphppage.php",
data: $("form").serialize(),
success: function(result)
{
updatechart(result);
}
});
Try this and you'll see what I mean:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#mybutt').click(function() {
$.ajax({
type: "POST",
url: "",
data: 'myVar=Hello',
success: function(data) {
alert(data);
}
});
});
}); //END $(document).ready()
</script>
</head>
<body>
Try this:<br />
<input type="button" id="mybutt" value="Click Me">
</body>
</html>

Categories

Resources