How to reload DataTables with ajax call on thymeleaf? - javascript

This is my html where I show the DataTable:
<tr>
<th>ID</th>
<th>Assurance</th>
<th>Credit Balance</th>
<th>Credit Result</th>
<th>Created Date</th>
<th style="text-align: center">Actions</th>
</tr>
</thead>
<tbody>
<tr th:each="credit: ${credits}">
<td th:text="${credit.id}"/>
<td th:text="${credit.assurance}"/>
<td th:text="${credit.creditBalance}"/>
<td th:text="${credit.creditResult}"/>
<td type="date" pattern="yyyy-MM-dd" th:text="${credit.creationDate}"/>
This is the endpoint:
#PreAuthorize("hasRole('ROLE_ADMIN')")
#GetMapping("/showList")
public ModelAndView showCreditList(){
ModelAndView mav = new ModelAndView("list-credits");
mav.addObject("credits",creditService.getAllCredits());
return mav;
}
And this is the script where I create the DataTable:
<script>
$(document).ready(function (){
$("#credit").DataTable();
})
</script>
I have no problem while creating this DataTable. But I tried so many ways like
$(document).ready(function() {
var table = $('#example').DataTable({
"ajax": "/api/data"
});
setInterval( function () {
table.ajax.reload();
}, 5000 );
});
Another try:
$(document).ready(function() {
var table = $('#example').DataTable({
columns: [
{ title: "Field 1" },
{ title: "Field 2" },
{ title: "Field 3" }
],
ajax: {
url: "/api/data",
dataSrc: function(data) {
var tableData = data.map(function(record) {
return [record.field1, record.field2, record.field3];
});
return tableData;
}
}
});
setInterval( function () {
table.ajax.reload();
}, 5000 );
});
But the problem is I am returning a List<Credit> from my endpoint. So ajax.reload simply can't format the data for DataTable. I am using this call from ajax.
#GetMapping("/all")
public List<Credit> getAllCredits(){
return creditService.getAllCredits();
}
Do you have any solution to this? How do I solve it?

Related

enable edit/delete in Datatables

I have a web app with cloud firestore as my backend. I used DataTable to export data from cloud firestore and display on the webpage, and the table looks like this:
Table
The code to load "orders" collection from cloud firestore and append to DataTables is:
var dataTable;
db.collection("orders").orderBy('timestamp', 'desc')
.get()
.then(function (querySnapshot) {
if (querySnapshot.size) {
var firestore_source = [];
querySnapshot.forEach(function (data) {
var obj = data.data();
obj.id = data.id;
firestore_source.push(obj);
});
//console.log('data:', firestore_source);
dataTable.clear();
dataTable.rows.add(firestore_source);
dataTable.order([0, 'desc']).draw();
}
})
.catch(function (error) {
console.log("Error getting documents: ", error);
});
$(document).ready(function () {
dataTable = $('#example').DataTable({
columns: [
{ data: 'Name' },
{ data: "Date" },
{ data: "Ins" },
{ data: "Phone" },
{ data: "Item" },
{ data: "Price"},
{ data: "Commision"},
{ data: "Revenue"},
{
data: null,
className: "center",
defaultContent: 'Edit / Delete'
}
],
"columnDefs": [
{"className": "dt-center", "targets": "_all"}
],
});
$('#example').on('click', 'a.editor_remove', function (e) {
e.preventDefault();
console.log("delete clicked");
console.log($(this).closest('tr'));
// what I should do here?
} );
});
And datatables in HTML:
<table id="example" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>Customer</th>
<th>Order Date</th>
<th>Instagram</th>
<th>Phone</th>
<th>Item</th>
<th>Price $</th>
<th>Commission</th>
<th>Earnings $</th>
<th>Edit / Delete</th>
</tr>
</thead>
</table>
Currently, the entire data within "orders" collection is loaded and obviously there are no features like editing and deleting data in each row.
So, I am stuck here that I have no idea how to identify each row in my table when clicking the edit/delete buttons on that row, so that I can use it as parameters to query cloud firestore?
I saw that there is built in tool Editor, but I am looking for native methods.
Regarding datatable API, You can get the clicked/selected row's data by this code which means you can get identity to edit or remove the selected row.
$('#example tbody').on('click', 'a.editor_remove', function () {
let row = dataTable.api().row($(this).closest("tr")).data();
console.log(row);
});

Script section works only in one view

I have a huge project in C# MVC. In one of the views, in index.cshtml, I have a code like this:
#model IEnumerable<Library.Models.Customer>
#{
ViewBag.Title = "Customers";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Klienci</h2>
<p>
#Html.ActionLink("Nowy klient", "New", "Customers", null, new { #class = "btn btn-primary" })
</p>
<table id ="customers" class="table table-bordered table-hover">
<thead>
<tr>
<th>Klient</th>
<th>Typ Czlonkostwa</th>
<th>Usun</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
#section scripts
{
<script>
$(document).ready(function () {
var table = $("#customers").DataTable({
ajax: {
url: "/api/customers",
dataSrc: ""
},
columns: [
{
data: "Name",
render: function(data, type, customer) {
return "<a href='/customers/edit/" + customer.Id + "'>" + customer.Name + "</a>";
}
},
{
data: "MembershipType.Name"
},
{
data: "Id",
render: function(data) {
return "<button class='btn-link js-delete' data-customer-id=" + data + ">Delete</button>";
}
}
]
});
$("#customers").on("click", ".js-delete",
function () {
var button = $(this);
if (confirm("Na pewno chcesz usunac?")) {
$.ajax({
url: "/api/customers/" + button.attr("data-customer-id"),
method: "DELETE",
success: function () {
//datatable methods - row, remove and draw
table.row(button.parents("tr")).remove().draw();
}
});
}
});
});
</script>
}
It works like a charm. But in another view, I have the code like this:
<table id="customers" class="table table-bordered table-hover">
<thead>
<tr>
<th>Ksiazka</th>
<th>Gatunek</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
#foreach (var book in Model)
{
<tr>
<td>#Html.ActionLink(book.Name, "Edit", "Books", new { id = book.Id }, null)</td>
<td>#book.Genre.Name</td>
<td>
<button class="btn-link" js-delete>Delete</button>
</td>
</tr>
}
</tbody>
#section scripts
{
<script>
$(document).ready(function() {
$("#customers .js-delete").on("click",
function() {
confirm("Sure?");
});
});
</script>
}
and it doesn't work. I mean, it compiles without any errors or warnings, but when I click Delete button nothing happens (should pop up confirm box).
What am I doing wrong?
If needed, I can provide whole code from these both views.
.js-delete means that "js-delete" is assumed to be a css class, while in the html it is an attribute. To search for elements with a particular attribute, you need "has attribute" selector:
$("#customers [js-delete]")

Can't load table from json using Javascript

I want create a table with JSON using Javascript and obtaining data from a database and show it on my page when I load it. This table thas to have a link to put the data in the selected row into textboxes.
To fill the table I use a method on .asmx:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false, XmlSerializeString = false)]
public void CargarUsuarios()
{
var wcf = new wsDN.ServicioClient();
var respuesta = wcf.Listar_Usuario().Valor.ToString();
Context.Response.ContentType = "application/json";
Context.Response.Write("{" + $"\"data\" : {respuesta}" + "}");
}
and this is how I create my table:
<table class="table table-bordered table-hover" id="tbl_Usuarios">
<thead>
<tr>
<th>ID Usuario</th>
<th>Cédula</th>
<th>Nombre</th>
<th>Apellidos</th>
<th>Usuario</th>
<th>Contraseña</th>
<th>Opciones</th>
</tr>
</thead>
</table>
and this is the JS:
<script src="js/main.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#tbl_Usuarios').DataTable({
"language": {
"url": "https://cdn.datatables.net/plug-ins/1.10.11/i18n/Spanish.json"
},
"ajax": {
"url": "/Contenido.asmx/CargarUsuarios",
"type": "POST",
"dataType": "json"
},
"columnDefs": [
{
"targets": 6,
"orderable": false,
"render": function (data, type, row) {
return 'Modificar';
}
}
]
});
});
</script>
Probably you need to add some library which will Add DataTable property/function to jquery/html element (do you use this jquery plugin datatables.net ? )

How to use angular ng-repeat for following JSON object?

I want to match headfield values with datafield, and have to fetch corresponding value into table data.
HTML:
<table>
<thead>
<tr>
<th ng-repeat="ReportsHead in ReportsHeadList">
{{ReportsHead.headerfield = ReportsHead.headfield}}
</th>
</tr>
</thead>
<tbody>
<tr>
<td ng-repeat="ReportsData in ReportsDataList"
ng-if="ReportsHead.headerfield == ReportsData.datafield">
{{ReportsData.value}}
</td>
</tr>
</tbody>
</table>
JSON Data :
$scope.ReportsHeadList = [
{
'headfield':'Contact Name'
},
{
'headfield':'Phone'
},
{
'headfield':'Email'
}
];
$scope.ReportsDataList = {
[
{
'datafield':'Contact Name',
'value':'Gunaseelan'
},
{
'datafield':'Phone',
'value':'8122911043'
},
{
'datafield':'Email',
'value':'G#gmail.com'
}
],
[
{
'datafield':'Contact Name',
'value':'Gunaseelan'
},
{
'datafield':'Phone',
'value':'8122911043'
},
{
'datafield':'Email',
'value':'G#gmail.com'
}
]
};
Thanks in advance.
First you should parse your Json with JSON.parse(json), and assigment the result to variable. e.g:
$scope.json = JSON.parse(json).
After, you can check for match headfield and data fields with for loop or map, e.g:
for(i in headfield) {
if (i === something)
return i
}
Hope the answar will help, if not leave a comment,
Good luck!

Datatable make cell clickable with href included in json itself

I am using bootstrap datatable to make a simple presentation of my json. I am using this json to feed datatable :
{
"manualList":[
{
"number":"WFC2062/05",
"umtype":"PT,SI",
"lang":"DE",
"cdnlink":"http://medias.bsh-partner.com/Documents/5550009686_A.pdf",
"version":"A",
"filelenght":1002357,
"urlstatus":true
},
{
"number":"WFC2062/05",
"umtype":"II,IU",
"lang":"DE",
"cdnlink":"http://medias.bsh-partner.com/Documents/5550009685_B.pdf",
"version":"B",
"filelenght":6377032,
"urlstatus":true
},
{
"number":"WFC2062/06",
"umtype":"PT,SI",
"lang":"DE",
"cdnlink":"http://medias.bsh-partner.com/Documents/5550009686_A.pdf",
"version":"A",
"filelenght":1002357,
"urlstatus":true
},
{
"number":"WFC2062/06",
"umtype":"II,IU",
"lang":"DE",
"cdnlink":"http://medias.bsh-partner.com/Documents/5550009685_B.pdf",
"version":"B",
"filelenght":6377032,
"urlstatus":true
},
{
"number":"WFC2062/07",
"umtype":"II,IU",
"lang":"DE",
"cdnlink":"http://medias.bsh-partner.com/Documents/9000029228_C.pdf",
"version":"C",
"filelenght":5918430,
"urlstatus":true
},
{
"number":"WFC2062/08",
"umtype":"II,IU",
"lang":"DE",
"cdnlink":"http://medias.bsh-partner.com/Documents/9000029228_C.pdf",
"version":"C",
"filelenght":5918430,
"urlstatus":true
}
],
"servicetype":"vibki",
"errormessage":null,
"warning":null
}
Data is in json format and i want to show hyperlink with column number, so my aim to add a column with the text of one manualList number and hyperlink of manuaList's cdnlink. But i don't know how to refer both of them inside one column.
Here is my script that creates datatable :
$(document).ready(function() {
var link = localStorage.getItem("link_url");
var table = $('#example').DataTable( {
"ajax": {
"url": link,
"dataSrc": "manualList"
},
"columns": [
{
"data": "cdnlink",
"render" : function(data, type, row, meta){
if(type === 'display'){
return $('<a>')
.attr('href', data)
.text()
.wrap('<div></div>')
.parent()
.html();
} else {
return data;
}
}
},
{ "data": "lang" }
]
});
$('#example')
.removeClass( 'display' )
.addClass('table table-striped table-bordered');
} );
link_url is giving ajax response that i've mentioned above, so you can this example json to evaluate the response.
Here is simple HTML that includes datatable as example :
<div class="container">
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Number</th>
<th>Language</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Number</th>
<th>Language</th>
</tr>
</tfoot>
</table></div>
I hope someone can help me, many thanks in advance for your responses!
I've checked below link to make column rendering on datatable :
https://datatables.net/examples/advanced_init/column_render.html
So, i've created one more invisible column to put cdnlink there and changed from columns to columnDefs such as :
$(document).ready(function() {
var link = localStorage.getItem("link_url");
var table = $('#example').DataTable( {
"ajax": {
"url": link,
"dataSrc": "manualList"
},
"columnDefs": [
{
"data" : "cdnlink",
"targets" : 2
}
,
{// The `data` parameter refers to the data for the cell (defined by the
// `data` option, which defaults to the column being worked with, in
// this case `data: 0`.
"data" : "number",
"render": function ( data, type, row ) {
return $('<a>')
.attr({target: "_blank",href: row.cdnlink})
.text(data)
.wrap('<div></div>')
.parent()
.html();
},
"targets": 0
},
{
"data" : "lang",
"targets" : 1
},
{ "visible": false, "targets": [ 2 ] }
]
});
$('#example')
.removeClass('display')
.addClass('table table-striped table-bordered');
} );
I've also added column in html file :
<div class="container">
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Number</th>
<th>Language</th>
<th>Link</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Number</th>
<th>Language</th>
<th>Link</th>
</tr>
</tfoot>
</table></div>
Then it worked like charm.

Categories