How to add ajax data in attribute in td element - javascript

In my ajax datatable I have this initialized:
"ajax": {
"url": "{{ route('cust_continfo_data_table') }}",
"dataType": "json",
"type": "POST",
"data": {
_token: "{{ csrf_token() }}",
cust_id_copy: $("#cust_id_copy").val()
}
},
"columnDefs": [{
'targets': 4,
'createdCell': function (td, cellData, rowData, row, col) {
$(td).attr('title', 'columns');
}
}
],
"columns": [{
"data": "id"
}, {
"data": "receipt_date"
}, {
"data": "info_division_name"
}, {
"data": "contact_status"
}, {
"data": "note"
}, {
"data": "created_at"
}, {
"data": "updated_at"
}
],
As you can see, I only have static value assigned which is column in:
$(td).attr('title', 'columns');
How can I add the dynamic value from "data":"note" ?

The rowData object should have the property note
'createdCell': function (td, cellData, rowData, row, col) {
$(td).attr('title', rowData.note);
}

Related

How to reduce repetition in Javascript code?

I have ASP.NET Code that use JS for datatable for views. And i do some repetiting code because i have 3 tables (in this case) that i have same columns. just the data(json) that different i have got from controller.
Here's the JS Code
<script type="text/javascript">
function parseDate(date) {
if (!date) {
return ""
}
return new Date(parseInt(date.substr(6))).toLocaleString();
}
$(document).ready(function() {
$.ajax({
"url": "#Url.Action("GetAllByUserToday", "Dashboard")",
"type": "GET",
"datatype": "json",
"success": function(res) {
const mapped = res.data.map((dt) => {
return {
...dt,
CreatedDate: parseDate(dt.CreatedDate),
Status: dt.Status ? "Sukses" : "Gagal",
IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
};
});
$("#getAllToday").DataTable({
"data": mapped,
"dom": 'Bfrtip',
"buttons": ['copy', 'excel'],
"columns": [
{ "data": "Nama" },
{ "data": "NoHP" },
{ "data": "Content" },
{ "data": "Sender" },
{ "data": "IsUsingTemplate" },
{ "data": "Status" },
{ "data": "CreatedDate" }
],
columnDefs: [{ 'targets': 0, type: 'date-euro' }],
order: [0, 'desc'],
});
}
});
$("#getAll_wrapper").addClass("w-100");
});
$(document).ready(function() {
$.ajax({
"url": "#Url.Action("GetAllSentByUserToday", "Dashboard")",
"type": "GET",
"datatype": "json",
"success": function(res) {
const mapped = res.data?.map((dt) => {
return {
...dt,
CreatedDate: parseDate(dt.CreatedDate),
Status: dt.Status ? "Sukses" : "Gagal",
IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
};
});
$("#getAllSentToday").DataTable({
"data": mapped,
"dom": 'Bfrtip',
"buttons": ['copy', 'excel'],
"columns": [
{ "data": "Nama" },
{ "data": "NoHP" },
{ "data": "Content" },
{ "data": "Sender" },
{ "data": "IsUsingTemplate" },
{ "data": "Status" },
{ "data": "CreatedDate" }
],
columnDefs: [{ 'targets': 0, type: 'date-euro' }],
order: [0, 'desc'],
});
}
});
});
$(document).ready(function() {
$.ajax({
"url": "#Url.Action("GetAllFailedByUserToday", "Dashboard")",
"type": "GET",
"datatype": "json",
"success": function(res) {
const mapped = res.data.map((dt) => {
return {
...dt,
CreatedDate: parseDate(dt.CreatedDate),
Status: dt.Status ? "Sukses" : "Gagal",
IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
};
});
$("#getAllFailedToday").DataTable({
"data": mapped,
"dom": 'Bfrtip',
"buttons": ['copy', 'excel'],
"columns": [
{ "data": "Nama" },
{ "data": "NoHP" },
{ "data": "Content" },
{ "data": "Sender" },
{ "data": "IsUsingTemplate" },
{ "data": "Status" },
{ "data": "CreatedDate" }
],
columnDefs: [{ 'targets': 0, type: 'date-euro' }],
order: [0, 'desc'],
});
}
});
});
</script>
Can I reduce the repetition for these code. If can, please help me. So I can try to apply for another page that has same issue. Thank you.
Update, suggestion from #Roamer-1888 finally I try this and it works!
function renderTable(action, tableId) {
$.ajax({
"url": action,
"type": "GET",
"datatype": "json",
"success": function(res) {
const mapped = res.data.map((dt) => {
return {
...dt,
CreatedDate: parseDate(dt.CreatedDate),
Status: dt.Status ? "Sukses" : "Gagal",
IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
};
});
$(tableId).DataTable({
"responsive": true,
"lengthChange": false,
"autoWidth": false,
"data": mapped,
"dom": 'Bfrtip',
"buttons": ['copy', 'excel'],
"columns": [
{ "data": "Nama" },
{ "data": "NoHP" },
{ "data": "Content" },
{ "data": "Sender" },
{ "data": "IsUsingTemplate" },
{ "data": "Status" },
{ "data": "CreatedDate" }
],
columnDefs: [{ 'targets': 0, type: 'date-euro' }],
order: [0, 'desc'],
});
}
});
}
$(document).ready(function() {
renderTable("#Url.Action("GetAllByUser", "Dashboard")", "#getByUser")
renderTable("#Url.Action("GetAllSentByUser", "Dashboard")", "#getSentByUser")
renderTable("#Url.Action("GetAllFailedByUser", "Dashboard")","getFailedByUser")
});

Sorting DataTables RowGroup

I'm using the jQuery DataTables plugin. I'd like to create a Datatables rowgroup by column1 and sorting single groups by column2. However when I sort column2, rowgroup doesn't work
var table = $('#DT_StatMov').DataTable({
"ajax": {
"url": url,
"type": "POST",
"datatype": "json"
},
"columns": [{
"data": "Name"
}, {
"data": "Product"
}, {
"data": "Date",
"render": function(data) {
return moment(data).format('D/M/Y');
}
}],
"orderFixed": [1, 'asc'],
"order": [2, 'desc'],
rowGroup: {
startRender: null,
endRender: function(rows, group) {
return group + ' (' + rows.count() + ')';
},
dataSrc: 'Product'
},
"scrollCollapse": true,
"search": {
"caseInsensitive": true,
},
"ordering": false,
"processing": true
});

How to assign an ID to a button in DataTables?

I have a table with some content and Edit button. This is the code which produces a datatable:
$(document).ready(function() {
var params = {};
callFunction("getAgentList", params,
function(bSuccess, res) {
var table = $('#example').DataTable({
data: res,
"columns": [
{ "data": "ID" },
{ "data": "Name" },
{ "data": "AltName1" },
{ "data": "AltName2" },
{ "data": "AltName3" },
{ "data": "AltName4" },
{ "data": "AltName5" },
{ "data": "AltName6" },
{ "data": "AltName7" },
{ "data": "AltName8" },
{ "data": "AltName9" },
{ "data": "AltName10" },
{
"orderable": false,
"data": null,
"defaultContent": '<button class="btn btn-warning" id='+res+' onclick="edit(this)">Edit</button>'
},
],
"order": [
[1, 'asc']
]
});
}
);
});
Each row should have an edit button for editing that specified row. For this I need an ID which I have in res JSON. But I am not sure how to get the ID for each of the edit buttons?
Right now if I put only res I get Object or with res.ID it is undefined. Which makes sense because I need to loop over the array...
Anyone?
EDIT
This is the res JSON:
{ AltName1: "Test1", AltName10: "", AltName2: "Test1Alt", AltName3: "Test1", AltName4: "Test1", ID: "1" }
{ AltName1: "Test2", AltName10: "", AltName2: "", AltName3: "", AltName4: "", ID: "2" }
If I set the id as <button class="btn btn-warning" id='+res[0].ID+' onclick="edit(this)">Edit</button>
Then all buttons have the same ID.
Change all the first letters to lowercase in JavaScript then use the render function of datatable:
{ "targets": 0, "data": 'iD' },
{ "targets": 1, "data": 'name' },
{ "targets": 2, "data": 'altName1' },
{ "targets": 3, "data": 'altName2' },
{ "targets": 4, "data": 'altName3' },
{ "targets": 5, "data": 'altName4' },
{ .... },
{
"targets": 6,
"data": 'iD',
"render": function (data, type, row, meta) {
return '<button class="btn btn-warning" id='+data+' onclick="edit(this)">Edit</button>'
}
}
In the render function you can access the ID with different ways :
1 : "data" : 'iD' then you use data (as I did)
2 : "data" : 'anything you want' then you use : row.iD
Also note please that you need to add a prefix before the ID to avoid repeated Id's (I always do that)
just try this
"defaultContent": '<button class="btn btn-warning" id='+ID+' onclick="edit('+ID+')">Edit</button>'

How to load Datatables from JSON object directly on Ajax success result?

After long time searching here around I can't find a solution to this problem, loading Datatables via Ajax GET is well documented but how can I use directly a JSON response after an Ajax POST?
This is my PHP function:
function getRelated() {
var elements = (document.getElementsByClassName('exashare'));
var query = [];
for(var i=0;typeof(elements[i])!='undefined';query.push(elements[i++].getAttribute('data-id')));
query = query.join(',');
$.ajax({
type: "POST",
url: baseUrl+"/requests/get_related.php",
data: "query="+query+'&_token='+_token,
cache: false,
success: function(html){
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
'url':jQuery.parseJSON(html),
"dataSrc": ""
},
"columns" : [
{ "data": "#" },
{ "data": "id" },
{ "data": "art" },
{ "data": "name" },
{ "data": "title" },
{ "data": "tag" },
{ "data": "likes" },
{ "data": "views" },
{ "data": "duration" },
{ "data": "time" }
]
});
}
});
}
The JSON on success looks like this:
{
"data": [{
"#": "1",
"id": "9",
"art": "default\/def8.jpg",
"name": "Simon The Cat",
"title": "Riflessioni sulla vita",
"tag": "riflessioni,vita,",
"likes": "1",
"views": "1024",
"duration": "185",
"time": "2015-11-30 19:36:31"
}, {
"#": "2",
"id": "15",
"art": "default\/def2.jpg",
"name": "Simon The Cat",
"title": "Riflessioni sulla morte",
"tag": "riflessioni,morte,",
"likes": "1",
"views": "1003",
"duration": "185",
"time": "2015-11-14 12:06:21"
},
...]
}
I also tried this:
//from this:
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
'url':jQuery.parseJSON(html),
"dataSrc": ""
},
...
//to this:
$('#example').DataTable( {
"ajax": jQuery.parseJSON(html),
...
But on console it always shows me the error "lenght of undefined".
I already tried to load data directly from a JSON file url
containing the same response here above and it works well.
How can I load JSON data on Ajax POST success results to populate my table?
Finally, after many tries, I found the solution that works with the latest Datatables release (1.10.13):
function getRelated() {
var elements = (document.getElementsByClassName('exashare'));
var query = [];
for(var i=0;typeof(elements[i])!='undefined';query.push(elements[i++].getAttribute('data-id')));
//parse as string
query = query.join(',');
$.ajax({
type: "POST",
url: baseUrl+"/requests/get_related.php",
data: "query="+query+'&_token='+_token,
cache: false,
success: function(html){
//html is a json_encode array so we need to parse it before using
var result = jQuery.parseJSON(html);
$('#example_ert').DataTable( {
//here is the solution
"data": result.data,
"ajax": {
"url": result,
"dataSrc": ""
},
"columns" : [
{ "data": "#" },
{ "data": "id" },
{ "data": "art" },
{ "data": "name" },
{ "data": "title" },
{ "data": "tag" },
{ "data": "likes" },
{ "data": "views" },
{ "data": "duration" },
{ "data": "time" }
]
});
}
});
}

JSON error on using jquery datatable

[{"name":"aaa","firstname":"bbb","lastname":"ccc"},
{"name":"qqq","firstname":"eee","lastname":"mmm"},
{"name":"www","firstname":"ooo","lastname":"lll"}]
I am making ajax request to server, its returning the above json data.But i >am getting the json parse error
$(document).ready(function() {
$('#example').dataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "http://example",
"dataType": "jsonp",
"columns": [
{ "data": "name"},
{ "data": "firstname" },
{ "data": "lastname" }
]
}
} );
});
Your ajax attribute should not contain the column attribute.:
Code:
$(document).ready(function() {
$('#example').dataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "http://example",
"dataType": "jsonp"
},
"columns": [
{ "data": "name"},
{ "data": "firstname" },
{ "data": "lastname" }
]
} );
});

Categories