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>
Related
So i'm trying to add data to datatable, i'm relatively new to Web Applications, i'm more of a mobile app developer
I've looked into a few examples and i've come up with a solution to do it, but for some reason i'm getting this error on chrome
DataTables warning: table id=personaliseDatatable - Ajax error. For more information about this error, please see http://datatables.net/tn/7
And if i check the console i'm getting Internal Server Error 500, but in fact the controller is getting triggered and i'm able to get the data from the repository, but its not able to return is what i'm able to understand
This is my method in controller
public JsonResult GetAllCapacityData()
{
try
{
var data = _capacityService.GetAllData(null).ToList();
return Json(new
{
data = data
});
}
catch (Exception ex)
{
_logger.Error("WebApp -> AreaMappingController -> GetAllData -> Catch -> ", ex);
throw;
}
}
and this is my ajax request
$(document).ready(function() {
if ($('#loaderDiv').hasClass("show")) {
$('#loaderDiv').removeClass("show");
}
GetCapacityData();
});
function GetCapacityData() {
$('#personaliseDatatable').DataTable({
responsive: true,
processing: false,
serverSide: false,
searching: true,
scrollX: true,
bDestroy: true,
"scrollX": true,
aaSorting: [0, 'desc'],
ajax: {
url: '#Url.Action("GetAllCapacityData", "Capacity")',
type: 'POST'
},
language: {
search: "",
searchPlaceholder: "Search...",
sInfoFiltered: ""
},
columns: [{
"render": function(data, type, full, meta) {
return meta.row + 1;
}
},
{
data: "data.ZoneMaster.ZoneName"
},
{
data: "CateogoryName"
},
{
data: "SubCateogoryName"
},
{
data: "ServiceType"
},
{
data: "UserType"
},
{
data: "Division"
},
{
data: "SlotName"
},
{
data: "AllowBooking"
},
{
data: "HoursBlockAhead"
},
{
data: "DaysOpenAheadForBooking"
},
{
data: "MaximumOrderCapacity"
},
{
mRender: function(data, type, row) {
return '<a class="actionLinks" data-toggle="tooltip" title="View Details" style="cursor:pointer;" onclick="EditCapacity(' + row.CapacityPlannerId + ')">Edit</a>';
},
sortable: false,
searchable: false
}
]
});
alert(data.ZoneMaster.ZoneId);
}
And this my Datatable
<div class="card-body">
<table style="width:100%" class="table table-striped table-hover table-bordered" id="personaliseDatatable">
<thead>
<tr>
<th>#</th>
<th>Zone</th>
<th>Cateogory</th>
<th>Sub Cateogory</th>
<th>Service Type</th>
<th>User Type</th>
<th>Division</th>
<th>Slot Name</th>
<th>Allow Booking</th>
<th>Hours to Block Ahead</th>
<th>Days Open Ahead</th>
<th>Max. Order Capacity</th>
<th>Action</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
Error on console
POST http://localhost:53201/Capacity/GetAllCapacityData 500 (Internal Server Error)
Any Help would be deeply appreciated
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
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>
I'm using datatable to show data from controller (i'm using Codeigniter) and need to show number column on the left table column.
I have tried:
$(document).ready(function() {
$('#booking_table').dataTable( {
processing: true,
serverSide: true,
language: dt_lang,
pagingType: "simple",
dom: 't<"col-sm-3 text-left"l><"col-sm-3"i><"col-sm-2"r><"col-sm-4 text-right"p>',
autoWidth : true,
ajax: {
"url" : base_url+"book/ajax_history",
"type" : "POST",
data : function (d){
d.show_filter = $('#_show_filter').val();
d.view_type = $('#_view_type').val();
}
},
columns: [
{
data : "b.booking_id",
visible : false,
},
{ data : null}, //where i should put index number
{ data : 'b.booking_date', className : "hidden-xs"},
{ data : 'b.from_name', className : "hidden-xs"},
{ data : 'b.to_name'},
],
responsive: false
});
// reference the table in a variable
var table = $('#booking_table').DataTable();
table.on( 'order.dt search.dt', function () {
table.column(0, {
search:'applied',
order:'applied'
}).nodes().each( function (cell, i) {
cell.innerHTML = i+1;
} );
} ).draw();
My Table:
<table class="table table-condensed" id="booking_table">
<thead>
<tr>
<th class="hidden-xs">id</th>
<th>No</th>
<th class="hidden-xs">
Tanggal
</th>
<th class="hidden-xs">
Pengirim
</th>
<th>
Penerima
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Refer to this https://www.datatables.net/examples/api/counter_columns.html
but, it's not working. What am I doing wrong ?
Please try below mentioned solution. Hope this will help you. Actually you initialized datatable two times.
$(document).ready(function() {
var table = $('#booking_table').dataTable({
processing: true,
serverSide: true,
language: dt_lang,
pagingType: "simple",
dom: 't<"col-sm-3 text-left"l><"col-sm-3"i><"col-sm-2"r><"col-sm-4 text-right"p>',
autoWidth: true,
ajax: {
"url": base_url + "book/ajax_history",
"type": "POST",
data: function(d) {
d.show_filter = $('#_show_filter').val();
d.view_type = $('#_view_type').val();
}
},
columns: [{
data: "b.booking_id",
visible: false,
},
{
data: null
}, //where i should put index number
{
data: 'b.booking_date',
className: "hidden-xs"
},
{
data: 'b.from_name',
className: "hidden-xs"
},
{
data: 'b.to_name'
},
],
responsive: false
});
table.on('order.dt search.dt', function() {
table.column(0, {
search: 'applied',
order: 'applied'
}).nodes().each(function(cell, i) {
cell.innerHTML = i + 1;
});
}).draw();
});
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
}