[{"name":"aaa","firstname":"bbb","lastname":"ccc"},
{"name":"qqq","firstname":"eee","lastname":"mmm"},
{"name":"www","firstname":"ooo","lastname":"lll"}]
I am making ajax request to server, its returning the above json data.But i >am getting the json parse error
$(document).ready(function() {
$('#example').dataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "http://example",
"dataType": "jsonp",
"columns": [
{ "data": "name"},
{ "data": "firstname" },
{ "data": "lastname" }
]
}
} );
});
Your ajax attribute should not contain the column attribute.:
Code:
$(document).ready(function() {
$('#example').dataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "http://example",
"dataType": "jsonp"
},
"columns": [
{ "data": "name"},
{ "data": "firstname" },
{ "data": "lastname" }
]
} );
});
Related
This question already has answers here:
use of comma and datatable decimals
(2 answers)
Closed 7 months ago.
I am reading a json file from remote url and displaying it in DataTable.
<script>
$(document).ready(function () {
$('#example').DataTable(
{
ajax: {
method: 'GET',
url: 'https://chainformed.s3.us-east-1.amazonaws.com/Data/mostwatched.json',
dataSrc: ''
},
paging: false,
responsive: true,
language: {
url: "//cdn.datatables.net/plug-ins/1.12.1/i18n/tr.json",
},
columns: [
{ "data": "id" },
{ "data": "rank" },
{ "data": "name" },
{ "data": "watchlist" },
{ "data": "percentage" },
{ "data": "difference" },
{ "data": "timestamp" }
]
});
$('.dataTables_length').addClass('bs-select');
});
</script>
I would like to be able to format and manipulate the data returned from that json file. What is the best way to do it?
For example, i would like to change the values from ({ "data": "watchlist" }) field to number format with comma. How can i achieve it?
I tried this but with no luck: https://datatables.net/reference/option/ajax.dataSrc
Use render element.
Read document from Format output data - orthogonal data
and example
Another way u can use columnDefs
<script>
$(document).ready(function () {
$('#example').DataTable(
{
ajax: {
method: 'GET',
url: 'https://chainformed.s3.us-east-1.amazonaws.com/Data/mostwatched.json',
dataSrc: ''
},
paging: false,
responsive: true,
language: {
url: "//cdn.datatables.net/plug-ins/1.12.1/i18n/tr.json",
},
columns: [
{ "data": "id" },
{ "data": "rank" },
{ "data": "name" },
{ "data": "watchlist" },
{ "data": "percentage" },
{ "data": "difference" },
{ "data": "timestamp" }
],
'columnDefs': [
{
"targets": 3,
"data": "watchlist",
"render": function ( data, type, row, meta ) {
return data.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
}
]
});
$('.dataTables_length').addClass('bs-select');
});
I have ASP.NET Code that use JS for datatable for views. And i do some repetiting code because i have 3 tables (in this case) that i have same columns. just the data(json) that different i have got from controller.
Here's the JS Code
<script type="text/javascript">
function parseDate(date) {
if (!date) {
return ""
}
return new Date(parseInt(date.substr(6))).toLocaleString();
}
$(document).ready(function() {
$.ajax({
"url": "#Url.Action("GetAllByUserToday", "Dashboard")",
"type": "GET",
"datatype": "json",
"success": function(res) {
const mapped = res.data.map((dt) => {
return {
...dt,
CreatedDate: parseDate(dt.CreatedDate),
Status: dt.Status ? "Sukses" : "Gagal",
IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
};
});
$("#getAllToday").DataTable({
"data": mapped,
"dom": 'Bfrtip',
"buttons": ['copy', 'excel'],
"columns": [
{ "data": "Nama" },
{ "data": "NoHP" },
{ "data": "Content" },
{ "data": "Sender" },
{ "data": "IsUsingTemplate" },
{ "data": "Status" },
{ "data": "CreatedDate" }
],
columnDefs: [{ 'targets': 0, type: 'date-euro' }],
order: [0, 'desc'],
});
}
});
$("#getAll_wrapper").addClass("w-100");
});
$(document).ready(function() {
$.ajax({
"url": "#Url.Action("GetAllSentByUserToday", "Dashboard")",
"type": "GET",
"datatype": "json",
"success": function(res) {
const mapped = res.data?.map((dt) => {
return {
...dt,
CreatedDate: parseDate(dt.CreatedDate),
Status: dt.Status ? "Sukses" : "Gagal",
IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
};
});
$("#getAllSentToday").DataTable({
"data": mapped,
"dom": 'Bfrtip',
"buttons": ['copy', 'excel'],
"columns": [
{ "data": "Nama" },
{ "data": "NoHP" },
{ "data": "Content" },
{ "data": "Sender" },
{ "data": "IsUsingTemplate" },
{ "data": "Status" },
{ "data": "CreatedDate" }
],
columnDefs: [{ 'targets': 0, type: 'date-euro' }],
order: [0, 'desc'],
});
}
});
});
$(document).ready(function() {
$.ajax({
"url": "#Url.Action("GetAllFailedByUserToday", "Dashboard")",
"type": "GET",
"datatype": "json",
"success": function(res) {
const mapped = res.data.map((dt) => {
return {
...dt,
CreatedDate: parseDate(dt.CreatedDate),
Status: dt.Status ? "Sukses" : "Gagal",
IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
};
});
$("#getAllFailedToday").DataTable({
"data": mapped,
"dom": 'Bfrtip',
"buttons": ['copy', 'excel'],
"columns": [
{ "data": "Nama" },
{ "data": "NoHP" },
{ "data": "Content" },
{ "data": "Sender" },
{ "data": "IsUsingTemplate" },
{ "data": "Status" },
{ "data": "CreatedDate" }
],
columnDefs: [{ 'targets': 0, type: 'date-euro' }],
order: [0, 'desc'],
});
}
});
});
</script>
Can I reduce the repetition for these code. If can, please help me. So I can try to apply for another page that has same issue. Thank you.
Update, suggestion from #Roamer-1888 finally I try this and it works!
function renderTable(action, tableId) {
$.ajax({
"url": action,
"type": "GET",
"datatype": "json",
"success": function(res) {
const mapped = res.data.map((dt) => {
return {
...dt,
CreatedDate: parseDate(dt.CreatedDate),
Status: dt.Status ? "Sukses" : "Gagal",
IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
};
});
$(tableId).DataTable({
"responsive": true,
"lengthChange": false,
"autoWidth": false,
"data": mapped,
"dom": 'Bfrtip',
"buttons": ['copy', 'excel'],
"columns": [
{ "data": "Nama" },
{ "data": "NoHP" },
{ "data": "Content" },
{ "data": "Sender" },
{ "data": "IsUsingTemplate" },
{ "data": "Status" },
{ "data": "CreatedDate" }
],
columnDefs: [{ 'targets': 0, type: 'date-euro' }],
order: [0, 'desc'],
});
}
});
}
$(document).ready(function() {
renderTable("#Url.Action("GetAllByUser", "Dashboard")", "#getByUser")
renderTable("#Url.Action("GetAllSentByUser", "Dashboard")", "#getSentByUser")
renderTable("#Url.Action("GetAllFailedByUser", "Dashboard")","getFailedByUser")
});
I have a jquery datatable that is populated by server side ajax. Supposedly, datatables are supposed to be sortable by default without having to add any parameters. Mine isn't. The sort arrows show up in the column headers and clicking on them flips the arrow but nothing gets sorted.
Here's the datatable definition:
$('#appPotTable').DataTable({
"ordering": true,
"processing": true,
"serverSide": true,
"ajax": "/MoneyMachine/screen_analystEst.php",
"columns": [
{ "data": "Symbol", "sortable":true },
{ "data": "CompanyName" },
{ "data": "StockType" },
{ "data": "ExDivDate" },
{ "data": "Dividend" },
{ "data": "DivYield" },
{ "data": "DivFrequency" },
{ "data": "DivPayDate" },
{ "data": "PriceToNav" },
{ "data": "AppreciationPotential" }
]
});
I've tried it with and without the "ordering" and "sortable" parameters but same result. I've also tried various column definition parameters with no joy. Suggestions?
Thanks to Ogreucha for suggesting to turn off server side processing. I did that and now sorting works fine. Here is the new code:
$('#appPotTable').DataTable({
"ajax": "/MoneyMachine/screen_analystEst.php",
"columns": [
{ "data": "Symbol" },
{ "data": "CompanyName" },
{ "data": "StockType" },
{ "data": "ExDivDate" },
{ "data": "Dividend" },
{ "data": "DivYield" },
{ "data": "DivFrequency" },
{ "data": "DivPayDate" },
{ "data": "PriceToNav" },
{ "data": "AppreciationPotential" }
]
});
After long time searching here around I can't find a solution to this problem, loading Datatables via Ajax GET is well documented but how can I use directly a JSON response after an Ajax POST?
This is my PHP function:
function getRelated() {
var elements = (document.getElementsByClassName('exashare'));
var query = [];
for(var i=0;typeof(elements[i])!='undefined';query.push(elements[i++].getAttribute('data-id')));
query = query.join(',');
$.ajax({
type: "POST",
url: baseUrl+"/requests/get_related.php",
data: "query="+query+'&_token='+_token,
cache: false,
success: function(html){
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
'url':jQuery.parseJSON(html),
"dataSrc": ""
},
"columns" : [
{ "data": "#" },
{ "data": "id" },
{ "data": "art" },
{ "data": "name" },
{ "data": "title" },
{ "data": "tag" },
{ "data": "likes" },
{ "data": "views" },
{ "data": "duration" },
{ "data": "time" }
]
});
}
});
}
The JSON on success looks like this:
{
"data": [{
"#": "1",
"id": "9",
"art": "default\/def8.jpg",
"name": "Simon The Cat",
"title": "Riflessioni sulla vita",
"tag": "riflessioni,vita,",
"likes": "1",
"views": "1024",
"duration": "185",
"time": "2015-11-30 19:36:31"
}, {
"#": "2",
"id": "15",
"art": "default\/def2.jpg",
"name": "Simon The Cat",
"title": "Riflessioni sulla morte",
"tag": "riflessioni,morte,",
"likes": "1",
"views": "1003",
"duration": "185",
"time": "2015-11-14 12:06:21"
},
...]
}
I also tried this:
//from this:
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
'url':jQuery.parseJSON(html),
"dataSrc": ""
},
...
//to this:
$('#example').DataTable( {
"ajax": jQuery.parseJSON(html),
...
But on console it always shows me the error "lenght of undefined".
I already tried to load data directly from a JSON file url
containing the same response here above and it works well.
How can I load JSON data on Ajax POST success results to populate my table?
Finally, after many tries, I found the solution that works with the latest Datatables release (1.10.13):
function getRelated() {
var elements = (document.getElementsByClassName('exashare'));
var query = [];
for(var i=0;typeof(elements[i])!='undefined';query.push(elements[i++].getAttribute('data-id')));
//parse as string
query = query.join(',');
$.ajax({
type: "POST",
url: baseUrl+"/requests/get_related.php",
data: "query="+query+'&_token='+_token,
cache: false,
success: function(html){
//html is a json_encode array so we need to parse it before using
var result = jQuery.parseJSON(html);
$('#example_ert').DataTable( {
//here is the solution
"data": result.data,
"ajax": {
"url": result,
"dataSrc": ""
},
"columns" : [
{ "data": "#" },
{ "data": "id" },
{ "data": "art" },
{ "data": "name" },
{ "data": "title" },
{ "data": "tag" },
{ "data": "likes" },
{ "data": "views" },
{ "data": "duration" },
{ "data": "time" }
]
});
}
});
}
Can anyone explain why TableTools (http://datatables.net/extensions/tabletools/) not show up.
I'm using the following js sources:
<script src="external/jquery/jquery.js"></script> //Version 1.10.2
<script src="jquery-ui.js"></script> //Version 1.11.2
<script src="jquery.dataTables.js"></script> // Version 1.10.4
<script src="dataTables.tableTools.js"></script> //Version 2.2.3
Thats the js for the datatable and tabletools.
$('#report-datatable').dataTable({
"processing": true,
"serverSide": false,
"paging": false,
"ajax": {
type: 'POST',
url: 'sources/report_table.php',
data: {
miDate: minval,
maDate: maxval,
retour: sap_retour,
hubew: sap_hubew,
nolkscan: nolkscan
}
},
"columns": [
{ "data": "LSAP" },
{ "data": "DatumSAP" },
{ "data": "Warenempfaenger" },
{ "data": "LSLK" },
{ "data": "DatumLK" }
],
"createdRow": function (row, data, index) {
if (data['LSLK'] == null){
$(row).css('background-color', 'lightcoral');
}
},
"dom": 'T<"fg-toolbar ui-widget-header ui-corner-tl ui-corner-tr ui-helper-clearfix"lr>t<"fg-toolbar ui-widget-header ui-corner-bl ui-corner-br ui-helper-clearfix"ip>',
"TableTools": {
"Buttons": [
"print",
{
"Extends": "collection",
"ButtonText": "Save",
"Buttons": [ "csv", "xls", "pdf" ]
}
]
},
"destroy": true
});
Everything works exprect the tabletools.
Thanks!
Solution:
$(document).ready(function() {
var report1table = $('#report1-datatable').dataTable();
function reporttable(minval,maxval,sap_retour,sap_hubew,nolkscan){
$.ajax({
type: 'POST',
url: 'sources/report_table_scans.php',
data: {
miDate: minval,
maDate: maxval,
retour: sap_retour,
hubew: sap_hubew,
nolkscan: nolkscan
},
success: function(result){
obj = JSON.parse(result);
loadDatatable(obj['data']);
},
error: function (result) {
alert('Fehler beim Laden der Daten. ' + result.responseText);
}
});
};
function loadDatatable(aaData){
report1table.dataTable({
"dom": 'Tti',
"deferRender": true,
"serverSide": false,
"paging": false,
"data": aaData,
"columns": [
{ "data": "LSAP" },
{ "data": "DatumSAP" },
{ "data": "Warenempfaenger" },
{ "data": "LSLK" },
{ "data": "DatumLK" }
],
"createdRow": function (row, data, index) {
if (data['LSLK'] == null){
$(row).css('background-color', 'lightcoral');
}
},
tableTools: {
"aButtons": [
"copy",
"print",
{
"sExtends": "collection",
"sButtonText": "Save",
"aButtons": [ "csv", "xls", "pdf" ]
}
]
},
"destroy": true
});
};