How can I add Id to row with jquery ajax server-side - javascript

I need to add id property to TR of table data dynamically added with jquery ajax server-side and write data there. how can I do that. I add the Json data coming with the code below to the lines.
"ajax": {
"url": '/Siparis/SiparisleriDoldur/',
"type": 'POST',
"dataType": 'json',
"data": { liste }
},
"columns":
[
{ "data": "MusteriAdi", "name": "Müşteri Adı" },
{ "data": "MalzemeAdi", "name": " Ürün Adı" },
{ "data": "SiparisAdet", "name": "Sipariş Adedi" },
],
i want to do;
<tr id='IdNumber' data-id='IdNumber'>
<td>bla</td>
<td>bla</td>
<td>bla</td>
</tr>
Note: IdNumber is in data(json list)

Given your use of the Datatable library you can use the createdRow property of the settings to amend each row as required. Try this:
$('#yourDatatable').dataTable({
"createdRow": function(row, data, dataIndex) {
let id = data[0]; // amend 'data[0]' here to be the correct column for your dataset
$(row).prop('id', id).data('id', id);
},
"ajax": {
// ...
},
// other settings as normal...
});

I fixed my problem with;
"createdRow": function (row, data) {
var id = data.Id;
$(row).prop('id', id).data('id', id);
$(row).attr('data-id', id).data('data-id', id);
},

Related

Add extra column to existing table populated with datatables

I am populating a table with datatables. The table has four columns always. But I need to add another column which can be shown or hidden based on boolean value.
My code so far:
{% show_extra_fields_button = show_extra_fields_bool %}
<table class="display" id="fields_datatable" class="fields_datatable">
<thead>
<tr>
<th>Name</th>
<th>Place</th>
<th>Email</th>
<th>Phone</th>
<th>Add Extra</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script src="/static/js/vendor/datatables.min.js"></script>
<script>
$(document).ready(function() {
$("#fields_datatable").dataTable({
ajax: {
"processing": true,
"dataSrc": "",
url: 'app/personFields/',
},
"columns": [
{ "data": "name" },
{ "data": "place" },
{ "data": "email" },
{ "data": "phone" },
]
})
if (show_extra_fields_button) {
$("#fields_datatable tr").each(function(){
$(this).append("<td><button>Add Extra</button</td>");
});
}
});
</script>
Here I would want to show the Add Extra column based on the boolean value. I want the header and the column values which will be buttons to be added using js.
How can I do that?
You can use data tables built-in functionality.
To add a button column you can use the following column definition:
{
"data": null,
"name": "buttonColumn",
"render": function (data, type, row) {
return '<button>Add Extra</button>';
}
}
Then use initComplete callback to set the columns' visibility once table has fully been initialised, data loaded and drawn:
$("#fields_datatable").dataTable({
ajax: {
type: "GET",
contentType: "application/json; charset=utf-8",
url: 'app/personFields/',
},
"columns": [
{ "data": "name" },
{ "data": "place" },
{ "data": "email" },
{ "data": "phone" },
{
"data": null,
"name": "buttonColumn",
"render": function (data, type, row) {
return '<button>Add Extra</button>';
}
}
],
"initComplete": function (settings, json) {
// get instance of datatable
table = settings.oInstance.api();
// get column using its name and set visibility
table.column('buttonColumn:name').visible(show_extra_fields_button);
}
});
You can put - instead of deleting that <td> for example <td>-</td>
You can add to the table header just the same way you are adding to the table body.
if (show_extra_fields_button) {
$('#fields_datatable thead tr').append('<th>Add Extra</th>')
}
Execute it just one time.

How can i grab an element from a row on a datatable?

I have a simple datatable that shows some JSON data, received from an API endpoint.
I added a column that will hold a button on each row of the table. This button, when hit, will fire an AJAX request with the value of id for that specific row.
This actual code works, but now, instead of only sending the value of id, i would also like to edit the table so that, when the button is hit, it will send the values of id and item for that row. Can someone give me some piece of advice on how to do that?
On another question, i've been told to use Data Attributes, but i don't really know how would i integrate this into my current code. Any advice is appreciated.
$(document).ready(function() {
$(document).on('click', '.btnClick', function() {
var statusVal = $(this).data("status");
console.log(statusVal)
callAJAX("/request_handler", {
"X-CSRFToken": getCookie("csrftoken")
}, parameters = {
'orderid': statusVal
}, 'post', function(data) {
console.log(data)
}, null, null);
return false;
});
let orderstable = $('#mytalbe').DataTable({
"ajax": "/myview",
"dataType": 'json',
"dataSrc": '',
"columns": [{
"data": "item"
}, {
"data": "price"
}, {
"data": "id"
},],
"columnDefs": [{
"targets": [2],
"searchable": false,
"orderable": false,
"render": function(data, type, full) {
return '<button type="button" class="btnClick sellbtn" data-status="replace">Submit</button>'.replace("replace", data);
}
}]
});
});
You could use the full parameter of the DataTables render function to store the values of the current seleceted row. In this way:
return '<button type="button" class="btnClick sellbtn" data-status="' + btoa(JSON.stringify(full)) + '">Submit</button>';
In the above code, the data-status data attribute will contains the stringified version of the current object value in base64 by using btoa(). In base64 because for some reason we cannot directly store the stringified version of the object in the button's data attribute.
Then, in the button's click event, you have to do:
Decode the stringified object by using atob().
Parse into object by using JSON.parse().
Something like this:
$(document).on('click', '.btnClick', function() {
var statusVal = $(this).data("status");
// Decode the stringified object.
statusVal = atob(statusVal);
// Parse into object.
statusVal = JSON.parse(statusVal);
// This object contains the data of the selected row through the button.
console.log(statusVal);
return false;
});
Then, when you click in the button you will see this:
So, now you can use this object to send in your callAJAX() function.
See in this example:
$(function() {
$(document).on('click', '.btnClick', function() {
var statusVal = $(this).data("status");
// Decode the stringified object.
statusVal = atob(statusVal);
// Parse into object.
statusVal = JSON.parse(statusVal);
// This object contains the data of the selected row through the button.
console.log(statusVal);
return false;
});
let dataSet = [{
"id": 1,
"item": "Item 1",
"price": 223.22
},
{
"id": 2,
"item": "Item 2",
"price": 243.22
},
{
"id": 3,
"item": "Item 3",
"price": 143.43
},
];
let orderstable = $('#myTable').DataTable({
"data": dataSet,
"columns": [{
"data": "item"
}, {
"data": "price"
}, {
"data": "id"
}, ],
"columnDefs": [{
"targets": [2],
"searchable": false,
"orderable": false,
"render": function(data, type, full) {
// Encode the stringified object into base64.
return '<button type="button" class="btnClick sellbtn" data-status="' + btoa(JSON.stringify(full)) + '">Submit</button>';
}
}]
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<link href="//cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" rel="stylesheet" />
<table id="myTable" class="display" width="100%"></table>
Hope this helps!

Adding an element within a td in jQuery datatable

I have a js data table that I have implemented for pagination of data. It uses the jQuery data table. The data is being displayed correctly. However, I want to add an element within the first row of the data table.
Before I added it like this : <td>#Html.ActionLink(item.CarId, "Detail", "Cars", new { id = item.CarId},null)
<span class="dt-expand-btn js-expand-btn">+</span></td>
What I want to add within the td of the js is : <span class="dt-expand-btn js-expand-btn">+</span>
var carsDataTable = $('.js-cars-lists').DataTable({
"ajax": {
"url": "/Cars/CarsPagination",
"processing": true,
"serverSide": true,
"language": {
"paginate": {
"previous": '<i class="material-icons">chevron_left</i>',
"next": '<i class="material-icons">chevron_right</i>'
}
},
"order": [0, "asc"],
"type": "POST",
"datatype": "json"
},
"columns": [
{
"data": "CarId", "name": "CarId", "autowidth": true,
"render": function (data, type, row, meta) {
$(row.CarId).css('color', 'red');
return '' + row.CarId + '';
}
},
{ "data": "CarName", "name": "CarName", "autowidth": true },
Could someone please help me to achieve this ? Also, paginate icons are not appearing. Please help.
jQuery DataTable has a function of render it accepts 4 parameters function(data, type, row) which you can control the rendering of your rows. You can now check the rows of a table and add your element in it.
You can use columnDefs method and then render:
...
columnDefs: [{
"render": function(data, type) {
return '<span class="dt-expand-btn js-expand-btn">+</span>';
},
"targets": 0
}]
...
targets refers to the index of the table column (since you are referring to the 1st column) set it to 0

Jquery datatables does not display the column headers

This is linked to the question here. However, my case is a bit different. I would like to implement the same datatables example from the other question which is here. As you can see you have to pass the column names to be able to initialize the table headers like below
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" }
]
The problem is that I would not know the header names beforehand as they will change. I've tried initializing the column names when I get the data from ajax like below using a 3rd variable (see where it says 'pay attention to this line' but this doesn't work.
//PAY ATTENTION TO THIS LINE
var columnsHeaders = [];
var ab = $('#dynamicScenarioTable').DataTable({
"bDestroy": true,
"dom": 'T<"clear">lfrtip',
"ajax": {
"type": "POST",
"url": "dynamicScenario.htm",
"data": tags,
"dataType": "json",
"dataSrc": function(json){
//PAY ATTENTION TO THIS LINE
columnsHeaders.push({"data": json.header });
return json.vals;
},
"error": function(exception)
{
displayMessageOnError();
}
},
//PAY ATTENTION TO THIS LINE
"columns": [columnsHeaders],
tableTools: tableDefaultS.tableTools
});
Any ideas?
You can add a data-source attribute to the TH tags that are built on your table header. You can then have jQuery read those and construct the array to send into the DataTable constructor.
<tr>
<th data-source="name">Name</th>
<th data-source="position">Postion</th>
<th data-source="start_date">Start Date</th>
</tr>
Then in your JavaScript do something like this to construct the array
var columnsHeaders = [];
$("#dynamicScenarioTable thead th").each(function() {
colmnsHeaders.push(
{
data : $(this).data("source")
}
);
});
// construct your DataTable after this

Post row datas from DataTable to an Ajax Form

I have a set of JSON data that are displayed using datatables. In one of the columns, I add a button and a text box only if the value in that column and another column meets a certain condition. this is the bit of code I used to do this:
$(document).ready(function (){
var alertTable = $('#alert-table').DataTable({
"jQueryUI": true,
"order": [ 3, 'desc' ],
"columns": [
{ "data": "source", "visible": false },
{ "data": "host" },
{ "data": "priority" },
{ "data": "ack", "render": function( data, type, row ) {
if (row.ack == "0" && row.priority > "2") {
return '<form><input class="ackname" type="text" value="Enter your name"><input class="ackbutton" type="button" value="Ack Alert" onclick="<get all items for that row and POST to a URL>"></form>';
}
return data;
}
},
],
"language": {
"emptyTable": "No Alerts Available in Table"
}
});
});
This works fine by adding a button and text in the cell. What I am looking to achieve is, when any of the button is been clicked, it should POST all the values for that row including what is typed in the text box to a URL which has another function that would extract those details and update the database and send back the refreshed data. I am new to datatables and jquery, any guide would be highly appreciated.
Have made some changes to the code, instead of form you can use div.
$(document).ready(function (){
var alertTable = $('#alert-table').DataTable({
"jQueryUI": true,
"order": [ 3, 'desc' ],
"columns": [
{ "data": "source", "visible": false },
{ "data": "host" },
{ "data": "priority" },
{ "data": "ack", "render": function( data, type, row ) {
if (row.ack == "0" && row.priority > "2") {
return '<div><input class="ackname" type="text" value="Enter your name"><input class="ackbutton" type="button" value="Ack Alert"></div>';
}
return data;
}
},
],
"language": {
"emptyTable": "No Alerts Available in Table"
}
});
$(document).on("click",".ackbutton",function() {
var currentIndex = $(this).parent().parent().index();
var rowData = alertTable.row( index ).data();
//extract the textbox value
var TextboxValue = $(this).siblings(".ackname").val();
var objToSave = {}; //Create the object as per the requirement
//Add the textbox value also to same object and send to server
objToSave["TextValue"] = TextboxValue;
$.ajax({
url: "url to another page"
data: JSON.stringify({dataForSave : objToSave}),
type: "POST",dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(datas) {
//Your success Code
},
error: function(error) {
alert(error.responseText);
}
});
});
});
Since both the pages are in same project, you can also do it using single ajax, passing all the values to server at once and then calling the other page internally from server and passing in the values using query string.
This is not a running code, rather to give you a basic idea on how to proceed.
Hope this helps :)

Categories