How to load a jQuery.DataTables grid with dynamic JSON data - javascript

I'm trying to load some simple JSON data into a jQuery.DataTables (datatables.net), The grid is showing up as it is defined in the HTML, but does not change based on the new data.
What am I missing? any suggestion?
HTML:
<table id="example" class="display" style="width:100%;">
<thead>
<tr>
<th>Id</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
</tr>
</tbody>
JavaScript: (jQuery and jQuery.DataTables are loaded)
$(document).ready(function () {
$("#example").DataTable({
data: [{ Id: "1" }, { Id: "2" }],
columns: { data: "Id", title: "ID" }
});
});

Your column data should be set of Array. Something like this
$(document).ready(function () {
$("#example").DataTable({
data: [{ Id: "1" }, { Id: "2" }],
columns: [{ data: "Id", title: "ID" }]
});
});
For Dynamic Data using ajax
$(document).ready(function() {
$('#example').DataTable( {
"ajax": "data/objects.txt",
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" }
]
} );
} );
JSON txt file
{
"data": [
{
"id": "1",
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
},
{
"id": "2",
"name": "Garrett Winters",
"position": "Accountant",
"salary": "$170,750",
"start_date": "2011/07/25",
"office": "Tokyo",
"extn": "8422"
}
]
}
More detail Here

Try this
var options = {
data: [{ Id: "1" }, { Id: "2" }],
columns: { data: "Id", title: "ID" }
}
var dataTable = $("#example").DataTable(options );
// Reload and refresh
dataTable.draw();

So, the my code for injecting the JSON data (or as a variable) is fine, the problem was another click event for the grid that I forgot I added before the initialization of that grid (bad bad me)
$("#example " + "tbody").on("click", "tr", function () {
var data = table.row(this).data();
isDebug && console.log('You clicked on ' + data[0] + '\'s row');
isDebug && console.log(data);
});

Related

JQuery datatable event modify button

I was working on a web application with JQuery datatables in it, and I have ran into some issues.
I am using the detailsTable.on('click', 'button.edit', function () { ... }) function to catch clicking events on buttons with a class "edit". It is working just fine, and I figured out, that i can get the row data with using detailsTable.row($(this).parents('tr')).data();. But it contains only the data I recived in the ajax call.
My idea is to change the html of the button I clicked on, but I can't find any solution, how to modify it. (I'd like to modify only in this row.)
Any ideas?
My html:
<table id="datatable" class="table table-bordered table-striped table-hover table-sm table-head-fixed">
<thead>
<tr>
<th>Value 1</th>
<th>Value 2</th>
<th>Actions</th>
</tr>
</thead>
</table>
My javascript:
$(function () {
var mytable = $("#datatable").DataTable({
"ajax": {"url": "", dataSrc: "data"},
"columns": [
{ "data": "val_2" },
{ "data": "val_1" }
],
"columnDefs": [
{
"targets": 2,
"render": function ( data, type, full, meta ) {
return '<button type="button" class="edit btn btn-info btn-sm" data-subid="'+full['id']+'"><i class="fa fa-wrench"> Edit</i></button>';
},
},
}
});
$('#datatable tbody').off('click')on('click', 'button.edit', function () { // Delete token
var data = mytable.row($(this).parents('tr')).data();
// I'd like to change the button, (I need to change the title, the fa-icon and the class, so basicely the whole html) like the way i did with "columnDefs"
});
});
Instead of accessing the source data values using data(), you can access the node using node(). Also, because you want to change the clicked button, you can get the <td> node for the cell in which the button is placed, instead of getting the row:
var td = mytable.cell($(this).parents('td')).node();
This can then be manipulated using jQuery or JavaScript - for example:
$( td ).find( 'button' ).html('I was ckicked');
Demo:
var dataSet = [
{
"id": "123",
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
},
{
"id": "456",
"name": "Donna Snider",
"position": "Customer Support",
"salary": "$112,000",
"start_date": "2011/01/25",
"office": "New York",
"extn": "4226"
},
{
"id": "567",
"name": "Cedric Kelly",
"position": "Senior Javascript Developer",
"salary": "$433,060",
"start_date": "2012/03/29",
"office": "Edinburgh",
"extn": "6224"
},
{
"id": "432",
"name": "Airi Satou",
"position": "Accountant",
"salary": "$162,700",
"start_date": "2008/11/28",
"office": "Tokyo",
"extn": "5407"
},
{
"id": "987",
"name": "Brielle Williamson",
"position": "Integration Specialist",
"salary": "$372,000",
"start_date": "2012/12/02",
"office": "New York",
"extn": "4804"
}
];
$(document).ready(function() {
var mytable = $('#datatable').DataTable( {
lengthMenu: [ [2, -1] , [2, "All"] ],
data: dataSet,
columns: [
{ title: "ID", data: "id" },
{ title: "Name", data: "name" },
{ title: "Office", data: "office" },
{ title: "Position", data: "position" },
{ title: "Start date", data: "start_date" },
{ title: "Extn.", data: "extn" },
{ title: "Salary", data: "salary" }
],
"columnDefs": [
{
"targets": 2,
"render": function ( data, type, full, meta ) {
return '<button type="button" class="edit btn btn-info btn-sm" data-subid="'+full['id']+'"><i class="fa fa-wrench"> Edit</i></button>';
},
},
]
} );
$('#datatable tbody').off('click').on('click', 'button.edit', function () { // Delete token
var td = mytable.cell($(this).parents('td')).node();
$( td ).find( 'button' ).html('I was ckicked');
});
} );
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">
</head>
<body>
<div style="margin: 20px;">
<table id="datatable" class="display dataTable cell-border" style="width:100%">
</table>
</div>
</body>
</html>

Data is not populated in data table with array objects, getting blank screen

Data is not populated in data table with array objects, getting blank screen. Tried with below code, any issue pls suggest
$('#example3').DataTable( {
data:storedJsonData,
"columns": [
{ "data": "id" },
{ "data": "name" },
{ "data": "position" },
{ "data": "salary" },
{ "data": "start_date" },
{ "data": "office" },
{ "data": "extn" }
]
} );
Fiddle
Data is not populated because columns header is case sensitive and must equal to given data.
I fix your data and columns header. Now it's work and show your data on DataTable.
var storedJsonData = [{
"id": "1",
"name": "abc",
"position": "Accountant",
"office": "Tokyo",
"Age": "63",
"start_date": "2011/07/25",
"salary": "$170,750",
"extn": "2"
},
{
"id": "2",
"name": "def",
"position": "Accountant",
"office": "Tokyo",
"Age": "63",
"start_date": "2011/07/25",
"salary": "$170,750",
"extn": "2"
}
];
$('#example3').DataTable({
data: storedJsonData,
"columns": [{
"data": "id"
},
{
"data": "name"
},
{
"data": "position"
},
{
"data": "salary"
},
{
"data": "start_date"
},
{
"data": "office"
},
{
"data": "extn"
}
]
});
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css" media="screen" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
<table id="example3" class="display" style="width:100%">
</table>

Show JSON Data in Jquery Datatables

I've been trying to get my JSON data in jQuery DataTables component.
First I wrote the JavaScript code as well as a view as shown in the code below:
$(document).ready(function () {
$('#myData').DataTable({
lengthChange: false,
ajax: {
url: "http://amp-local/api/wipbin/FetchChild/",
// dataSrc: 'allk'
},
columns: [
{ data: "name" },
{ data: "numbers" }
],
select: true
});
});
My view:
<table id="myData" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Numbers</th>
</tr>
</thead>
</table>
My JSON:
[{
"numbers": "38",
"name": "Bllaca"
}, {
"numbers": "28",
"name": "Kaess"
}, {
"numbers": "27",
"name": "droessmer"
}, {
"numbers": "24",
"name": "friedricha"
}]
Result is with this error:
TypeError: undefined is not an object (evaluating 'f.length')
And my table is empty.
When using server-side processing with AJAX requests, it expects JSON data to be returned in the special format required by DataTables. The following fields of JSON response object are required: draw, data, recordsTotal and recordsFiltered. You need to bring your server response into accordance with expected format.
For example, your first response should be as following:
{
"draw": 1,
"recordsTotal": 4,
"recordsFiltered": 4,
"data": [
{
"numbers": "38",
"name": "Bllaca"
}, {
"numbers": "28",
"name": "Kaess"
}, {
"numbers": "27",
"name": "droessmer"
}, {
"numbers": "24",
"name": "friedricha"
}
]
}

Rendering DataTable rows from json file

I am trying to render DataTable-rows from a json file, placed on the same directory. But unfortunately, the DataTable-Body stays empty, and no error is displayed in the console.
Here is the (reduced) HTML-Code:
<table id="opTable">
<thead>
<tr><th class="partner_id">ID</th><th>ShortName</th><th>DisplayName</th><th>LogoUrl</th><th>Incent</th><th>JTS-URL</th></tr>
</thead>
<tbody>
</tbody>
</table>
Here is the JavaScript I am using to load the data from the json file:
<script>
$(document).ready(function() {
$('#onlinePartnerTable').DataTable({
"ajax" : "../test2.json",
"columns": [{
"data": "pId"
}, {
"data": "shrName"
}, {
"data": "DplayName"
}, {
"data": "lgo"
}, {
"data": "inc"
}, {
"data": "featured"
}]
});
});
</script>
and here is a sample of my json file:
{
"partnerList": [
{
"shrname": "bchan",
"Dplayname": "bchang-Shop",
"pId": "id12345",
"featured": "0",
"lgo": "https://url.here.com/url",
"inc": "1 to 1",
"dets": {
"tmage": "someUrl/here",
"desp": "desciption",
"jturl": "jtUrl/here",
"jtbut": "Shop",
"termy": [
{
"heady": "",
"body": ""
}
]
}
},
{
"shrname": "hereIsIt",
"Dplayname": "HereIs-Shop",
"pId": "id65432",
"featured": "0",
"lgo": "https://url.here.com/url",
"inc": "2 to 1",
"dets": {
"tmage": "someUrl/here",
"desp": "desciption",
"jturl": "jtUrl/here",
"jtbut": "Shop",
"termy": [
{
"heady": "",
"body": ""
}
]
}
}
]
}
I am becomming this error now.. See the image below.
try this
var t = [{
"shrname": "bchan",
"Dplayname": "bchang-Shop",
"pId": "id12345",
"featured": "0",
"lgo": "https://url.here.com/url",
"inc": "1 to 1",
"dets": {
"tmage": "someUrl/here",
"desp": "desciption",
"jturl": "jtUrl/here",
"jtbut": "Shop",
"termy": [{
"heady": "",
"body": ""
}]
}
}, {
"shrname": "hereIsIt",
"Dplayname": "HereIs-Shop",
"pId": "id65432",
"featured": "0",
"lgo": "https://url.here.com/url",
"inc": "2 to 1",
"dets": {
"tmage": "someUrl/here",
"desp": "desciption",
"jturl": "jtUrl/here",
"jtbut": "Shop",
"termy": [{
"heady": "",
"body": ""
}]
}
}];
$(document).ready(function() {
$('#opTable').DataTable({
"aaData": t,
"columns": [{
"data": "pId"
}, {
"data": "shrname"
}, {
"data": "Dplayname"
}, {
"data": "lgo"
}, {
"data": "inc"
}, {
"data": "featured"
}]
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdn.datatables.net/1.10.11/css/jquery.dataTables.min.css" />
<script src="https://cdn.datatables.net/1.10.11/js/jquery.dataTables.min.js"></script>
<table id="opTable">
<thead>
<tr>
<th class="partner_id">ID</th>
<th>ShortName</th>
<th>DisplayName</th>
<th>LogoUrl</th>
<th>Incent</th>
<th>JTS-URL</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Based on one of the links Turnip provided in the comments, Datatables Ajax Data Source (objects), your data should look like this:
{
"data": [
{
"shrname": "bchan",
"Dplayname": "bchang-Shop",
"pId": "id12345",
"featured": "0",
"lgo": "https://url.here.com/url",
"inc": "1 to 1",
},
{
"shrname": "hereIsIt",
"Dplayname": "HereIs-Shop",
"pId": "id65432",
"featured": "0",
"lgo": "https://url.here.com/url",
"inc": "2 to 1",
}
]
}
I'm not sure what you're trying to do with the "dets" part of your data though

Populate javascript.datatables with json?

I am trying to have a javascript.datatable (http://www.datatables.net/) show a dataset which I have passed through as a json string.
$(document).ready(function () {
$('#Reports').html('<table cellpadding="0" cellspacing="0" border="0" class="display" id="ReportsTable"></table>');
var data = <%=jsonResult%>;
$('#ReportsTable').dataTable({
"data": data,
"columns": [
{ "title": "id" },
{ "title": "name" },
{ "title": "regAndId" },
{ "title": "type" },
{ "title": "timeStamp" }
]
});
});
My jsonResult or data variable looks as follows:
{
"reports": [
{
"id": "421b4b9b-63d5-4fe2-a929-a85d9fe9d2ef",
"name": "TAMANYA PROPERTIES",
"regAndId": "1989/011313/23",
"timeStamp": "2014/10/31 01:57:51 PM",
"type": "Company"
},
{
"id": "56751c5d-84b2-463a-95be-9feb2fa02c10",
"name": "TESTA PROPERTY COMPANY PTY",
"regAndId": "1980/004250/07",
"timeStamp": "2014/10/31 10:29:09 AM",
"type": "Company"
}
]
}
The error I am getting is:
Uncaught TypeError: undefined is not a function
This could happens if the DataTable library is not loaded properly. First jQuery should be loaded and then dataTables.
Assuming you have properly included both jQuery and DataTables libraries, you need to configure the columns according to your data structure. Something like this should work for you:
$(document).ready(function () {
$('#Reports').html('<table cellpadding="0" cellspacing="0" border="0" class="display" id="ReportsTable"></table>');
var data = {
"reports": [
{
"id": "421b4b9b-63d5-4fe2-a929-a85d9fe9d2ef",
"name": "TAMANYA PROPERTIES",
"regAndId": "1989/011313/23",
"timeStamp": "2014/10/31 01:57:51 PM",
"type": "Company"
},
{
"id": "56751c5d-84b2-463a-95be-9feb2fa02c10",
"name": "TESTA PROPERTY COMPANY PTY",
"regAndId": "1980/004250/07",
"timeStamp": "2014/10/31 10:29:09 AM",
"type": "Company"
}
]
};
$('#ReportsTable').dataTable({
"data": data.reports,
"columns": [
{ "data": "id" },
{ "data": "name" },
{ "data": "regAndId" },
{ "data": "type" },
{ "data": "timeStamp" }
]
});
});
See demo
Try change this
var data = <%=jsonResult%>;
to
var data = '<%=jsonResult%>';
Note the quotes.
This is needed as the content you are assigning is expecting json string and not just an object/function.

Categories

Resources