Colum Custom Datatables with Object Javascript or JSON - javascript

I am currently using a CRUD made with NodeJS + MYSQL. I recently integrated my tables with Jquery Datatables Plugins, but I would like to add a custom column in which to return any information as a prefix in the ID.
example, a column of the type
ID | NAME | CPF | ACTIONS
01 | JAIR | 123 | IAMID01
I was reading something about object mapping but the maximum I got was that.
db.js
exports.execSQLQuery = (sqlQry, res) => {
var connection = mysql.createConnection({
host : 'localhost',
port : 3306,
user : 'root',
password : '',
database : 'nodejs'
});
connection.query(sqlQry, function(error, results, fields){
if(error)
res.json(error);
else
//*PASSAR RESULTADO PARA UMA VARIAVEL
//var rows = JSON.parse(JSON.stringify(results[0]));
res.json(results);
connection.end();
console.log('executou!');
});
};
tabela.html
<script type="text/javascript">
$(document).ready(function(){
$.get('/dados',function(dados){
// data is a JS object parsed from a JSON response
var ids = dados.map(elemento => elemento.ID);
console.log(ids)
$('#example').DataTable({
"ajax":{
"url":"/dados",
"dataSrc": ""
},
"columns":[
{ "data":"ID"},
{ "data":"Nome"},
{ "data":"CPF"},
{
data: null,
className: "center",
defaultContent: ids
}
]
});
});
});
</script>
</head>
<body>
<table id="example" class="table table-striped table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Office2</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Office2</th>
</tr>
</tfoot>d
</table>
</body>
clientesController.js
module.exports = {
getDados : function(req,res){
execSQLQuery('SELECT * FROM Clientes',res);
},

You should alter your table and add the column as an self-incremental field.
ID Integer PRIMARY KEY AUTOINCREMENT
After that every new record in your table will autogenerate a new id.

Related

json.parse not working with template engine handlebars

I have a search box which I wish to use to populate my table so i want to access the data sent to the view template in the script tag
ERROR IN SCRIPT
1 Uncaught SyntaxError: "[object Object]" is not valid JSON
at JSON.parse (<anonymous>)
at 1:164:25
<div class="FieldElement2" style="margin-top: 3%;">
<div class="input-field ">
<input id="search_masterTable" type="text" class="validate">
</div>
<table class="highlight centered responsive-table" style="width: min-content;" >
<thead>
<tr>
<th></th>
<th>Ledg.No.</th>
<th>File No.</th>
<th>Name</th>
<th>Phone</th>
</tr>
</thead>
<tbody id="searchResultsBody">
{{#each accounts_array}}
<tr>
<td><button class="viewButton">View Chart</button></td>
<td class="Ledg_No" scope="row">{{ledger_num}}</td>
<td class="File_Num" scope="row">{{file_num}}</td>
<td class="Name">{{client_name}}</td>
<td class="gPhoneNumber3">{{phone_number6}}</td>
</tr>
{{/each}}
</tbody>
</table>
</div>
<script>
document.getElementById('search_masterTable').addEventListener('input',()=>{
const search_value = document.getElementById('search_masterTable').value.toUpperCase().split(' ')
// NOT WOKING
const data = JSON.parse("{{accounts_array}}")
const result_array = data.filter(function(r){
return search_value.every(function(word){
console.log(word)
return column_name_array.some(function(colIndex){
console.log(r[colIndex])
if(r[colIndex] == null){
return false
}else{
return r[colIndex].toString().toUpperCase().indexOf(word) !== -1
}
});
});
})
function to_populate_masterTable(){
}
</script>
insted of sending the search value back to the server i want to perfom the search opearation in the frontend and send display the result for every search input
BACK END
router.get('/masterTable/:id', ensureAuth, async (req, res) => {
const title = 'Master Table'
var account = parseInt(req.params.id)
db.query(`SELECT * FROM mt_`+account+``, async (err,accounts_array) => {
res.render('masterTable', {
accounts_array,
title
})
})
})
THIS IS WHAT THE account_array LOOKS LIKE
[
RowDataPacket { // <= this is the error
id: 1,
ledger_num: 'VM364',
file_num: 'VM364',
client_name: 'MUTHU KUMAR',
phone_number1: '9791716460',
status: 'UNSETTLED'
},
RowDataPacket {
id: 1,
.,
.,
.,
},
RowDataPacket {},
RowDataPacket {}
]
error that i got
Uncaught SyntaxError: Unexpected token '{' (at 1:169:21)
This might work by first stringifying the variable and using the tag syntax to pass the stringified JSON to the template:
const data = JSON.parse(<%= JSON.stringify(accounts_array) %>);

passing data from loop to front-end

I have this function on my backend:
app.get('/dashboard', async(req, res) => {
const customers = await stripe.customers.list();
customers.data.forEach(customer => {
console.log(customer.metadata);
});
res.render('dashboard.ejs', {customer: customers})
})
and on my front end:
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>NAME</th>
<th>EMAIL</th>
<th>ACTIONS</th>
</tr>
</thead>
<tbody>
<% if(customer.length){
for(var i = 0;i < customer.length;i++) { %>
<tr>
<td><%=customer[i].NAME%></td>
<td><%=customer[i].EMAIL%></td>
<% }
}else{ %>
<% } %>
</tbody>
</table>
however, i am trying to pass the METADATA to the front end. and within the metadata object, i have name and email. So on the front end, i tried:
<%=customer[i].METADATA.NAME%>
but it returned nothing. and same on the backend. how can i fix this?
In the comments above, by fetch I mean the term fetch you need to some how connect to your backend to accept the data on front end. You can use ajax, axios, fetch API etc.... Below I used ajax to show how to get data from back end. Feel free to comment if you have any questions?
var data_from_backend;
$.ajax({
type: 'GET',
data: 'data_to_send_to_backend',
url: 'server_URL',
success: function(getMetadata) {
$.each(JSON.parse(getMetadata), function(myMetadata) {
data_from_backend = myMetadata.the_name_of_data_set_on_backend
})
},
error: function(data) {
console.log('Something went wrong.');
}
});
console.log(data_from_backend)

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);
});

Datatables json data displaying all data on one line

I am trying to setup datatables to read my json API to display data in a table. Currently it is outputting all of the object contents into one line instead of looping it like a table should be displayed.
My jsfiddle
HTML
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Blocks</th>
<th>Amount</th>
<th>Date</th>
</tr>
</thead>
</table>
JS
$(document).ready(function() {
$('#example').DataTable({
"processing" : true,
"ajax" : {
"url" : "https://zelcash.voidr.net/api/payments",
dataSrc : ''
},
"columns" : [ {
"data" : "payments.[].blocks.[]"
}, {
"data" : "payments.[].amounts.t1XHpNtYY2N3EMDRoX9RM2hq4DWWPZSmawJ"
}, {
"data" : "payments.[].time"
}]
});
});
You need an endpoint to return only an array, because this endpoint https://zelcash.voidr.net/api/payments return some objects.
You can check the datatables documentation:
https://datatables.net/examples/data_sources/ajax in this example the ajax url is https://datatables.net/examples/ajax/data/arrays.txt and this return an array.

How to get AJAX response before sending to template using DATATABLES?

I am implementing a log tables in my admin panel and I used the datatable plugin.
I created an ajax in my datatable but I don't know how to get the response before sending to the table.
I have this in my jquery:
<script type="text/javscript">
$(document).ready(function() {
$('#log-pageview')
.on('xhr .dt', function(e, settings, json) {
$('#status').html(json.status)
})
.dataTable({
"processing": true,
"serverSide": true,
"ajax": "/secure/logs/visits.php?log_get=1"
});
});
</script>
In my HTML I have this:
<table id="log-pageview" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Log ID</th>
<th>User ID</th>
<th>IP Address</th>
<th>Date Viewed</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Log ID</th>
<th>User ID</th>
<th>IP Address</th>
<th>Date Viewed</th>
</tr>
</tfoot>
</table>
<div id="status"></div>
In my server side PHP I have this.
function get_pageview() {
$host = mysql_connect('localhost','avjunky_2','1qaz2wsx') or die(mysql_error());
mysql_set_charset('utf8', $host); //added for character encoding, made it global for functions /** added by rochelle **/
$db = mysql_select_db('avjunky_2',$host) or die(mysql_error());
$log_array = array();
$log_data = array();
$get_all_logs = mysql_query("SELECT id, logged_id, ip_address, date_viewed FROM avjunky_pageview", $host);
while($row_logs = mysql_fetch_array($get_all_logs)) {
$log_data[] = array(
'id' => $row_logs['id'],
'logged_id' => $row_logs['logged_id'],
'ip_address' => $row_logs['ip_address'],
'date_viewed' => $row_logs['date_viewed']
);
}
$total_count = count($log_data);
$log_array = array(
'draw' => 1,
'recordsTotal' => $total_count,
'recordsFiltered' => $total_count,
'data' => $log_data
);
echo json_encode($log_array);
}
if(isset($_GET['log_get'])) {
get_pageview();
}
In the server side I generated this kind of json:
{"draw":1,"recordsTotal":2,"recordsFiltered":2,"data":[{"id":"3","logged_id":"7","ip_address":"122.2.55.11","date_viewed":"2015-03-16 10:10:42"},{"id":"2","logged_id":"8","ip_address":"122.2.55.11","date_viewed":"2015-03-17 00:05:40"}]}
{
"draw":1,
"recordsTotal":2,
"recordsFiltered":2,
"data":[
{
"id":"3",
"logged_id":"7",
"ip_address":"122.2.55.11",
"date_viewed":"2015-03-16 10:10:42"
},
{
"id":"2",
"logged_id":"8",
"ip_address":"122.2.55.11",
"date_viewed":"2015-03-17 00:05:40"
}
]
}
I don't know where did I go wrong. I checked the developer tool network tab and it seems that the ajax is not calling the URL.
In my AJAX I also tried to call the response from the URL like this.
http://mysite/admin/secure/logs/visits.php?log_get=1
But it doesn't load the data as well.
Firstly, to use xhr.dt datatables > 1.10 should be used.
Secondly, the data should be of the following structure.
{
"draw":1,
"recordsTotal":2,
"recordsFiltered":2,
"data":[
[
"3",
"7",
"122.2.55.11",
"2015-03-16 10:10:42"
],
[
"2",
"8",
"122.2.55.11",
"2015-03-17 00:05:40"
]
]
}
Here is a demo

Categories