load json data in bootstrap data table - javascript

i created a table using html . now i want to populate my table using json data. i have been using the example https://www.youtube.com/watch?v=A20PY5RxdI8
my javascript code is here
$(document).ready(function () {
$.getJSON("my.php", function(json){
myjson = json;
}).done(function() {
$('#tble').bootstrapTable('load', myjson);
var $table = $('#tble');
$table.bootstrapTable('load', myjson);
$table.bootstrapTable({
search: true,
pagination: true,
buttonsClass: 'primaryt',
showFooter: true,
minimumCountColumns: 2,
columns: [ {
field: 'one',
title: 'ID'
}, {
field: 'two',
title: 'f name'
}, {
field: 'three',
title: 'last name'
}],
data: myjson
});
});
});
<table id = 'tble'>
<tr class=xl70 height=42 style='mso-height-source:userset;height:31.5pt'>
<th height=42 class=xl72 width=57 style='height:31.5pt;border-top:none;
border-left:none;width:43pt' data-field="one">1</th>
<th class=xl72 width=80 style='border-top:none;border-left:none;width:60pt'>2</th>
<th class=xl72 width=97 style='border-top:none;border-left:none;width:73pt'>3</th>
</tr>
</table>
i want to populate json into my table but it does not display any data in the said table

You can use the following code example:
$.getJSON("my.php")
.done(function(data) {
$('#tble').bootstrapTable('load', data);
})
Read the $.getJson() documentation for more example.

I have checked the documentation of Bootstrap table which you are using in your example.
The document is poorly written without explaining the parameters. Which results in confusion. When you read the document and do some JS fiddle you will realise that data-toggle attribute is very important. The value of this attribute should be the same as the Id of your table.
you can try removing data attribute filed in below fiddle to verify it.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://unpkg.com/bootstrap-table#1.15.3/dist/bootstrap-table.min.css" rel="stylesheet">
<script src="https://unpkg.com/bootstrap-table#1.15.3/dist/bootstrap-table.min.js"></script>
<div id="toolbar">
<button id="button" class="btn btn-secondary">load</button>
</div>
<table
id="table"
data-toggle="table"
data-height="460">
<thead>
<tr>
<th data-field="id">ID</th>
<th data-field="name">Item Name</th>
<th data-field="price">Item Price</th>
</tr>
</thead>
</table>
<script>
var $table = $('#table')
var $button = $('#button')
function randomData() {
var startId = ~~(Math.random() * 100)
var rows = []
for (var i = 0; i < 10; i++) {
rows.push({
id: startId + i,
name: 'test' + (startId + i),
price: '$' + (startId + i)
})
}
return rows
}
$(function() {
var someData = randomData();
debugger;
$table.bootstrapTable('load', someData)
})
</script>

You will need to modify your code as below.
HTML
<table id = 'tble' data-toggle="tble">
<thead>
<tr>
<th data-field="one">ID</th>
<th data-field="two">f name</th>
<th data-field="three">last name</th>
</tr>
</thead>
</table>
and JS
$(document).ready(function () {
$('#table').bootstrapTable({
url: 'my.php',
pagination: true,
search: true,
columns: [{
field: 'one',
title: 'ID'
}, {
field: 'two',
title: 'f name'
}, {
field: 'three',
title: 'last name'
}]
})
});
Note: your URL should return a json response. Else instead of getJSON you can use $.ajax

Related

datatable column filtering with serverside(ajax) doesn't work (with django)

I'm developing with django and javascript with datatable.
I want to apply column filtering in my datatable
(https://datatables.net/extensions/fixedheader/examples/options/columnFiltering.html)
but it works fine without serverside option & ajax (in client side),
but it doesn't work with serverside option & ajax.
How can i FIX IT? Please help me..
this is my code.
<table id="sample_table" class="table table-bordered table-hover">
<thead>
<tr>
<th class="sample_id">ID</th>
<th>date</th>
<th>serial</th>
<th>name</th>
<th>birth</th>
</tr>
</thead>
<tbody id="sample_table_body">
</tbody>
<tfoot>
<tr>
<th>ID</th>
<th>date</th>
<th>serial</th>
<th>name</th>
<th>birth</th>
</tr>
</tfoot>
</table>
</div>
<!-- /.card-body -->
</div>
var column_list = [
{ "data" : "id" , "className": "sample_id"},
{ "data" : "receiving_at" },
{ "data" : "serialnumber" },
{ "data" : "name" },
{ "data" : "birthday" },
];
$('#sample_table tfoot th').each(function(){
var title = $("#sample_table thead th").eq( $(this).index() ).text();
$(this).html('<input type="text" placeholder="Search '+title+'" />' );
});
var sample_table = $('#sample_table').DataTable({
"paging": true,
"autoWidth": false,
"lengthChange": false,
"ordering": true,
"processing" : true,
"columns": column_list,
"order": [ [0, 'desc'] ],
"fixedHeader": true,
"orderCellsTop": true,
"ajax": {
url: '/view_datatable/',
type: 'POST'
},
"serverSide" : true, //get data from server
"initComplete": function() { // column filtering RUN after table loaded .
$( '#sample_table tfoot input' ).on( 'keyup change clear', function () {
if ( sample_table.search() !== this.value && this.value.length>0) {
search_result = sample_table.search( this.value );
search_result.draw();
}
} );
}
});
#view.py
def list_datatable(request, companyname):
context = {}
if(request.method == "POST"):
start_page = int(request.POST['start'])
order_direction = request.POST["order[0][dir]"] # direction of ordering(asc, desc)
order_col_no = request.POST["order[0][column]"] # number of index to sort
order_col_name = request.POST['columns[' + str(order_col_no) + '][data]'].strip() # name of colum of ordering
sample_list_all = Sample.objects.all().order_by(order_col_name)
sample_list_per_page = []
for idx, obj in enumerate(sample_list_all[start_page:start_page + 10]):
data = {}
data['id'] = obj.id
data['receiving_at'] = str(obj.receiving_at)
data['birthday'] = obj.birthday
data['serialnumber'] = obj.serialnumber
data['name'] = obj.name
sample_list_per_page.append(data)
#-- end of --#
datalist_to_json = json.dumps(
{"data": sample_list_per_page, "recordsFiltered": len(sample_list_all), "recordsTotal": len(sample_list_all)}
)
return HttpResponse(datalist_to_json, content_type="application/json")

HTML Table update with AJAX not getting rendered

I am a newbie for all this AJAX stuff, however I am trying to see how I can update a html table using AJAX.
I am using flask which is initially populating the HTML Table then I submit a form to run a query and the new data is returned to me. with that new data I want the AJAX to update the table. In my Ajax call there is already a HighCharts graph that is correctly working I am mostly focusing on the table part.
If you see in the AJAX I have a variable flatOrderedDictList this variable is what I am focusing on how do i render the table with this updated data in AJAX? I a bit confused on that?
my html page with table that I want ajax to update
<div style="padding-left: 20px; padding-right: 20px; padding-bottom: 50px;">
<table class="table table-hover">
<thead>
<tr>
<th scope="col">User</th>
<th scope="col">Customer</th>
<th scope="col">Profile</th>
<th scope="col">Role</th>
<th scope="col">Image</th>
<th scope="col">Packet Size</th>
<th scope="col">Ingress Port Use</th>
<th scope="col">Egress Port Use</th>
<th scope="col">Date</th>
</tr>
</thead>
<tbody>
{% for item in flatOrderedDictList %}
<tr>
{% for key, value in flatOrderedDictList[loop.index0].items() %}
<td>{{value}}</td>
{%endfor%}
</tr>
{%endfor%}
{% endif %}
</tbody>
</table>
</div>
my ajax code
$(document).ready(function() {
$('form').on('submit', function(event) {
$.ajax({
data : {
images: $('#images').val(),
userID: $('#userID').val(),
release: $('#release').val(),
rsp_type: $('#rsp_type').val(),
lc_type: $('#lc_type').val(),
featuer_type: $('#featuer_type').val(),
chassis_type: $('#chassis_type').val(),
profile_name: $('#profile_name').val(),
os_type: $('#os_type').val(),
daterange: $('#daterange').val(),
role: $('#role').val(),
customer: $('#customer').val(),
queryCount: $('#queryCount').val(),
flatOrderedDictList: $('#flatOrderedDictList').val()
},
type : 'POST',
url : '/performance_reports_query_result'
})
.done(function(data) {
if (data.error) {
$('#errorAlert').text(data.error).show();
$('#successAlert').hide();
}
else {
console.log('customer is ' + customer + 'flatOrderedDictList is ' + data.flatOrderedDictList + data.flatOrderedDictList.length);
$('#successAlert').text('Successfully Found ' + data.queryCount + ' Results').show();
$('#errorAlert').hide();
}
$(function () {
Highcharts.setOptions({
lang: {
thousandsSep: ','
}
});
$('#container').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Performance Results Run'
},
legend: {
title: {
text: 'Applied Featuers <br/><span style="font-size: 9px; color: #666; font-weight: normal">(Click to hide)</span><br>--------<br>',
style: {
fontStyle: 'italic'
}
},
},
xAxis: [{
categories: data.image_list_query,
tickColor: 'black',
lineColor: 'black',
lineWidth: 1,
labels: {
style:{
color: 'black',
},
}
},
{
linkedTo: 0,
opposite: true,
categories: data.oid_list,
labels: {
style:{
color: 'red',
display: 'none'
},
}
},
{
linkedTo: 0,
lineColor: 'white',
tickColor: 'black',
categories: data.customer_name_listAjax,
labels: {
style:{
color: 'black',
// display: 'none'
},
}
}
],
yAxis: {
min: 0,
title: {
text: 'Packets Per Second'
}
},
credits: {
enabled: false,
text: 'mastarke'
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
series: {
cursor: 'pointer',
point: {
events: {
click: function() {
var tableDate = this.category;
var clickedOid = this.series.chart.options.xAxis[1].categories[this.index];
var image = this.category;
window.location.href = '/performance_reports_detail' + clickedOid;
}
}
}
}
},
series: [{
name: 'FRAME SIZE',
data: data.framesize_list
},
{
name: 'Baseline PPS',
data: data.baseline_traffic_value_list
},
{
name: 'Performance With Features',
data: data.PerformanceWithFeatures_list
},
]
});
});
});
event.preventDefault();
});
});
from the JS console this is what is returned.
JS Console Pic 1
I do not understand if you want to bring or insert data, but I leave one way how render html with js vanilla.
Remember if you want do this dynamic, it's different, this way only works when your call your api one time.
RENDER
async function insertData() {
const route = 'your api route';
const response = await fetch(`${route}`);
const json = await response.json();
const thead = document.querySelector('#myThead');
for (const i in json) {
/* I don't know the response of your api then this code is if you response it's only a object with de values
example
json = {
User,
Customer,
etc,
etc,
}
*/
if (json.hasOwnProperty(i)) {
const element = json[i];
thead.innerHTML +=
`
<th scope="col">${element}</th>
`;
}
}
}
OUTPUT HTML
<thead id="myThead">
<tr>
<th scope="col">User</th>
<th scope="col">Customer</th>
<th scope="col">Profile</th>
<th scope="col">Role</th>
<th scope="col">Image</th>
<th scope="col">Packet Size</th>
<th scope="col">Ingress Port Use</th>
<th scope="col">Egress Port Use</th>
<th scope="col">Date</th>
</tr>
</thead>

Two footers not printed in pdf and excel format when clicked in button in jquery datatable

Actaullay I have buttons to save in pdf and excel format.I have two footers coming from json as Total and Percentage.When i click the Button then only Total footer is coming but the Percentage row is not coming in the pdf and excel files.I need to show both the footer but it is not coming.
<table id="report46Table" class="display responsive nowrap" style="width: 100%">
<thead>
<tr>
<th>Disturbance</th>
<th>Zero</th>
<th>Minor</th>
<th>Medium</th>
<th>Major</th>
<th>Total</th>
<th>Occurance</th>
</tr>
</thead>
<tfoot>
<tr id="fTotal">
<th>Total</th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr id="fPercentage">
<th>Total</th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot>
</table>
script to load the datatable is:
<script>
$(document).ready(function() {
var report46Data = [];
var report46Footer = null;
var report46Table = $('#report46Table').DataTable({
data : report46Data,
dom: 'Bfrtip',
buttons: [
'copy',
{
extend: 'excel',
footer: true,
text : 'Export to Excel',
messageTop: 'Records of forest disturbances in the forest',
filename: function(){
return 'report46';
},
},
{
extend: 'pdfHtml5',
footer: true,
//orientation : 'landscape',
pageSize: 'TABLOID',
text : 'Export to Pdf',
messageTop: 'Records of forest disturbances in the forest',
title: '',
filename: function(){
return 'report46';
},
},
],
ordering: false,
"paging" :false,
columns : [ {
"data" : "disturbanceName"
}, {
"data" : "iZero"
}, {
"data" : "iMinor"
}, {
"data" : "iMedium"
} ,{
"data" : "iMajor"
},{
"data" : "total"
},{
"data" : "occurance"
}],
"footerCallback" : function(row, data, start, end, display) {
var api = this.api();
if (report46Footer) {
$($("#fTotal")[0].cells[0]).html(report46Footer[0].disturbance);
$($("#fTotal")[0].cells[1]).html(report46Footer[0].iZero);
$($("#fTotal")[0].cells[2]).html(report46Footer[0].iMinor);
$($("#fTotal")[0].cells[3]).html(report46Footer[0].iMedium);
$($("#fTotal")[0].cells[4]).html(report46Footer[0].iMajor);
$($("#fTotal")[0].cells[5]).html(report46Footer[0].total);
$($("#fTotal")[0].cells[6]).html("");
$($("#fPercentage")[0].cells[0]).html(report46Footer[1].disturbance);
$($("#fPercentage")[0].cells[1]).html(report46Footer[1].iZero);
$($("#fPercentage")[0].cells[2]).html(report46Footer[1].iMinor);
$($("#fPercentage")[0].cells[3]).html(report46Footer[1].iMedium);
$($("#fPercentage")[0].cells[4]).html(report46Footer[1].iMajor);
$($("#fPercentage")[0].cells[5]).html(report46Footer[1].total);
$($("#fPercentage")[0].cells[6]).html("");
}
}
});
$.ajax({
url : A_PAGE_CONTEXT_PATH + "/api/report46/all",
method : "GET",
dataType : "json",
success : function(response) {
report46Data = response.dataList;
report46Footer = response.footer;
report46Table.rows.add(report46Data).draw();
}
});
});
</script>

Populating a DataTable with an object equal to an array of objects

I have a DataTable structured like the following:
<div class="table-responsive">
<table class="table table-striped table-condensed table-bordered" id="mainSutable2" style="width: 100%">
<thead>
<tr>
<th>Comment Time</th>
<th>ID</th>
<th>Status</th>
<th>Comment</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
var mainSutable2 =$('#mainSutable2').DataTable({
paging: false,
ordering: true,
info: true,
oLanguage:{
sProcessing: 'No Data To Display', //change language of default "Processing" dialogue
sSearch: 'Filter'
},
data: trackingNotes,
columns: [
{ data: "ID" },
{ data: "comment" },
{ data: "dt" },
{ data: "status"}
]
});
I am trying to populate this table using the following: Please note MainSutable is another table that has a row that include the object value.
var trackingNotes = {};
trackingNotes = mainSutable.row(this).data().tracking_notes;
//tracikingNotes equals the following
/*
Object {tracking_note: Array[2]}
tracking_note: Array[2]
0:Object
ID: "12345"
comment: "yo"
dt: "2016-06-06 12:50:46.0"
guid: "9999"
status: "1"
1:Object
ID: "12346"
comment: "hey"
dt: "2016-06-08 12:50:46.0"
guid: "9999"
status: "2"
*/
If anyone has any tips of information that could lead me in the right direction, it would be greatly appreciated.
Not sure why it's not working on your side. I've tried replicating the problem but it's working for me and the data is displayed in the DataTable maybe there's an issue with the script references to dataTable.js or maybe you're not calling the binding logic inside the document load.
Copy and paste the example below in a new page and run it, you will see that it works.Figure out what's different in your code compared to mine and I'm sure it will help you solve the problem:
<head runat="server">
<title></title>
<link href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="//code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script>
$(function () {
var trackingNotes = [];
var note1 = { ID: "1", comment: "comment1", dt: new Date(), guid:"1", status: "1" };
var note2 = { ID: "2", comment: "comment 2", dt: new Date(), guid: "2", status: "1" };
var note3 = { ID: "3", comment: "comment 3", dt: new Date(), guid: "3", status: "0" };
trackingNotes.push(note1);
trackingNotes.push(note2);
trackingNotes.push(note3);
var mainSutable2 = $('#mainSutable2').DataTable({
paging: false,
ordering: true,
info: true,
oLanguage: {
sProcessing: 'No Data To Display', //change language of default "Processing" dialogue
sSearch: 'Filter'
},
data: trackingNotes,
columns: [
{ data: "ID" },
{ data: "comment" },
{ data: "dt" },
{ data: "status" }
]
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="table-responsive">
<table class="table table-striped table-condensed table-bordered" id="mainSutable2" style="width: 100%">
<thead>
<tr>
<th>Comment Time</th>
<th>ID</th>
<th>Status</th>
<th>Comment</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</form>
</body>

jQuery AJAX loading page content

I'm trying to rebuild my site, so that it uses AJAX to load data content inside a div.
This is the function, that handles the loading:
navigate = function(url, title, callback){
//show message to user
toastr.info('<i class="fa fa-spin fa-circle-o-notch"></i> Page is being loaded, please wait.');
//default variables set
title = title || url.substr(url.lastIndexOf('/') + 1).replace(/_/g, ' ').capitalize();
callback = callback || function(){};
//load content to wrapper
$("#content-wrapper").load(url + "?" + $.param({page_load: true}), function(res, status, jqXHR){
toastr.clear(); //hides message
if(status === "error")
{
toastr.error('Page couldn\'t be loaded. Please try again later or contact your system administrator', jqXHR.status + ": " + jqXHR.statusText);
}
else if(status === "success")
{
History.pushState({page: url}, title + " | PCexpres manager", url);
}
//remove modals from inside the content and move them to the end of body - prevents problems with backdrop
$('body > .modal').remove();
$('.modal').each(function(){
$(this).clone(true, true).appendTo("body");
$(this).remove();
})
//execute custom callback
callback(res, status, jqXHR);
})
}
The problem is, that the content, which is being loaded, often (usually) contains more JS (libraries as well as script tags with my code), which is usually not executed correctly. Example of such response:
<script type="text/javascript" src="http://pce.local/assets/js/plugins/datatables/datatables.js?1434971835"></script>
<script type="text/javascript" src="http://pce.local/assets/js/plugins/datatables/extensions/ColReorder/js/dataTables.colReorder.min.js?1434972105"></script>
<link type="text/css" rel="stylesheet" href="http://pce.local/assets/css/plugins/datatables/datatables.css?1434971143" />
<script>
$(function() {
$('.table').dataTable({
dom: 'Rlfrtip',
stateSave: true,
processing: true,
serverSide: true,
searchHighlight: true,
ajax: "http://pce.local/technician/customers/index_processing.json",
columns: [{
data: "checkbox",
name: "return 'id'"
}, {
data: "id",
name: "return 'id'"
}, {
data: "last_name",
name: "return 'last_name'"
}, {
data: "first_name",
name: "return 'first_name'"
}, {
data: null,
render: function(customer) {
return customer.address + (((customer.address_city !== "" || customer.address_zip !== "") && (customer.address !== "")) ? ", " : "") + customer.address_zip + " " + customer.address_city;
},
name: "return 'first_name'"
}, {
data: "email",
name: "return 'email'"
}, {
data: "phone1",
name: "return 'phone1'"
}, {
data: "actions",
name: "return 'id'"
}],
stateSave: true,
order: [
[1, "desc"]
],
aoColumnDefs: [{
'bSortable': false,
'aTargets': [0, -1]
}],
iDisplayLength: 50,
language: {
lengthMenu: "Display <select><option value='25'>25</option><option value='50'>50</option><option value='100'>100</option><option value='200'>200</option><option value='500'>500</option></select> records per page"
}
});
$(".check_all").change(function() {
$(".content_wrapper :checkbox").prop("checked", $(this).is(":checked"))
})
$("#delete_checked").click(function() {
var ids = '';
$(".delete_one:checked").each(function() {
ids += $(this).attr('data-id') + ',';
})
//remove last comma
ids.slice(0, -1)
if (confirm('Are you sure?'))
window.location.href = "http://pce.local/technician/customers/delete/" + ids
})
$(document).on('click', '.delete_customer', function(e) {
e.preventDefault();
$me = $(this);
bootbox.dialog({
title: "Delete customer?",
message: "Are you sure, you want to delete this customer?",
buttons: {
nope: {
label: "No",
className: "btn-default",
callback: function() {
toastr.success('Deletion cancelled');
}
},
yep: {
label: "Yes",
className: "btn-warning",
callback: function() {
window.location.href = $me.attr('href');
}
},
yeah: {
label: "Yes, delete data as well",
className: "btn-danger",
callback: function() {
window.location.href = $me.attr('href') + '/1';
}
}
}
});
})
});
</script>
<div class="content_wrapper">
<a class="btn btn-primary btn-md" href="http://pce.local/technician/customers/add">+</a>
<table class="table table-condensed table-striped table-hover pce-list_table">
<thead>
<th>
<input class="check_all" name="check_all" value="1" type="checkbox" id="form_check_all" />
</th>
<th>ID</th>
<th>Last name</th>
<th>First name</th>
<th>Address</th>
<th>E-mail</th>
<th>Phone</th>
<th>Actions</th>
</thead>
<tfoot>
<th>
<input class="check_all" name="check_all" value="1" type="checkbox" id="form_check_all" />
</th>
<th>ID</th>
<th>Last name</th>
<th>First name</th>
<th>Address</th>
<th>E-mail</th>
<th>Phone</th>
<th>Actions</th>
</tfoot>
<tbody>
</tbody>
</table>
<button id="delete_checked" class="btn btn-primary btn-md" data-nosubmit="data-nosubmit" name="delete_checked">Delete checked</button>
</div>
Is there any proper way to load such content and execute the js as if it was a normal page load?
Here is the correct way to execute javascript after ajax response is added to the container
var arr = document.getElementById('myDiv').getElementsByTagName('script')
for (var n = 0; n < arr.length; n++)
{
eval(arr[n].innerHTML)//run script inside div
}

Categories

Resources