How to create a dynamic jquery data table with json data and ajax?
I made two modifications in your code and it seems to be working after that.
1) Added a div with id 'showData' after div 'info'.
<div id="showData">
</div>
2) Enclosed $('#action-button').click(function() in $(document).ready(function().
$(document).ready(function() {
$('#action-button').click(function() {
$.ajax({
url: 'https://api.myjson.com/bins/1oaye',
data: {
format: 'json'
},
error: function() {
$('#info').html('<p>An error has occurred</p>');
},
dataType: 'json',
success: function(data) {
// EXTRACT VALUE FOR HTML HEADER.
var col = [];
for (var i = 0; i < data.length; i++) {
for (var key in data[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < data.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = data[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
},
type: 'GET'
});
});
});
The error says that it expecting a div with id 'showData'.
How to create jquery data table from JSON array without declaring columns
var data = [{ "Number": "10031", "Description": "GYPROCK PLUS RE 10MM 1200X4200", "FarmLocation": "WH5", "LocationIn": "LINE_1C2AA", "Quantity": 18}, { "Number": "95844", "Description": "CEMINSEAL WALLBOARD RE 6MM 1350X3000", "FarmLocation": "WH5", "LocationIn": "LINE_1C2AB", "Quantity": 6}];
var $thead = $('#tableId').find('thead');var tr = $("<tr>");$thead.append(tr);var columns = [];$.each(data[0], function(name, value) { var column = { "data": name, "title":name }; columns.push(column);});
$('#tableId').DataTable({ data: data, columns: columns});
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script><script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<table id="tableId" class="table table-condensed responsive"> </table>
How to load a jQuery.DataTables grid with dynamic JSON data
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);
});
Creating a table to display json data with dynamic columns
Here you go with a solution https://jsfiddle.net/qpu3cn5u/
var data = [{"Customer Name":"XXXX","1999":76.000,"2000":68.000,"2001":49.000,"2002":41.000,"2003":47.000,"2004":56.000,"2005":33.000,"2006":51.000,"2007":56.000,"2008":52.000,"2009":55.000,"2010":52.000,"2011":57.000,"2012":55.000,"2013":93.000,"2014":92.000,"2015":62.000,"2016":71.833},{"Customer Name": "YYYY","1999":76.000,"2000":68.000,"2001":49.000,"2002":41.000,"2003":47.000,"2004":56.000,"2005":33.000,"2006":51.000,"2007":56.000,"2008":52.000,"2009":55.000,"2010":52.000,"2011":57.000,"2012":55.000,"2013":93.000,"2014":92.000,"2015":62.000,"2016":71.833}];
var colHeader = Object.keys(data[0]);
for(var i=0; i<colHeader.length; i++) { $('table thead tr').append('<th>' + colHeader[i] + '</th>');}
for(var i=0; i<data.length; i++){ $('table tbody').append('<tr></tr>') for(var j= 0; j<colHeader.length; j++){ $('table tbody tr').last().append('<td>' + data[i][colHeader[j]] + '</td>'); }}
th, td { border: 1px dashed #000; padding: 5px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><table> <thead> <tr></tr> </thead> <tbody></tbody></table>
how to load dynamic json to jquery datatable
Using your example data, loop over the first record as your 'example' data, then create the column definitions on the fly like so:
EDIT: example of original code with an xhr call to retrieve data
$(document).ready(function() { //callback function that configures and initializes DataTables function renderTable(xhrdata) { var cols = [];
var exampleRecord = xhrdata[0];
var keys = Object.keys(exampleRecord);
keys.forEach(function(k) { cols.push({ title: k, data: k //optionally do some type detection here for render function }); });
var table = $('#example').DataTable({ columns: cols });
table.rows.add(xhrdata).draw(); }
//xhr call to retrieve data var xhrcall = $.ajax('/path/to/data');
//promise syntax to render after xhr completes xhrcall.done(renderTable);});
How to use with Data Table jQuery with ajax?
the docs uses this syntax:
$('#dataTable-verify-pt').DataTable({
responsive: true,
ajax: "{{route('get.pt')}}",
columns:[
{data: "kode_pt"},
{data: "nama"},
{data: "validasi"},
]
});
Edit
you need to modify you response so it's an object like so:
{
"data": [
{"kode_pt":1,"nama":"title","SK_path":"\/folder","email_PJ":"\/images","validasi":0},
{"kode_pt":2,"nama":"title","SK_path":"\/folder","email_PJ":"\/images","validasi":0}
]
}
Edit 2
You can achieve so by modifying your response like so:
return response()->json(['data' => $data]);
How to convert a dynamic table to a jquery data table?
Just having a quick look at the DataTable code and it looks like the likely reason is that you haven't put the <th>
in a <thead>
section. Currently they sit within <tbody>
.
Here's the updated fiddle...
https://jsfiddle.net/8some9a0/1/
Related Topics
How to Format Numbers in Vuejs
Reactjs - Multiple If Conditions Inside Map Function
Access a Variable Outside of .Then Function
How to Highlight Parts of an Imagemap on Mouseover
How to Redirect Url After Login Successful Via Ajax Call in PHP
How to Show a Confirm Message Before Delete
React Router Dom Returns a Blank Page When Going to a Particular Route
Blob Download Is Not Working in Ie
How to Combine First Name and Last Name in JavaScript
Vuejs Error, Invalid Prop: Type Check Failed for Prop. Expected Date, Got Number With Value
Ios Safari/Chrome - Unwanted Scrolling When Focusing an Input Inside the Modal
Ngoninit Not Being Called When Injectable Class Is Instantiated
Syntaxerror: Unexpected Token O in Json At Position 1
Discord.Js Sending Message to Specific Channel
Window.Opener | Not Working in Chrome
Onclick Event Not Working on Google Chrome