The following JavaScript renders either a green checkmark button or a red X button in a jQuery datatable column:
{
data: "HasPayment",
render: function (data, type, row, meta) {
if (data) {
return '<button id=n-"' meta.row '"><span style="color: green"></span></button>';
}
return '<button id=n-"' meta.row '"><span style="color: red"></span></button>';
}
}
The following JavaScript is called when one of the buttons (green checkmark or red X) is clicked:
$('#HR_Payment_DataTable tbody').on('click', '.hasPayment', function () {
var id = $(this).attr("id").match(/\d /)[0];
var data = $('#HR_Payment_DataTable').DataTable().row(id).data();
var url = `Payment/Set?applicationId=${data[14]}&year=${data[12]}&month=${data[13]}&hasPayment=${data[11]}`;
$.ajax({
url: url,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
dataTable.ajax.reload();
},
error: () => {
console.error("500 Internal Server Error.");
}
});
});
When I click one of the buttons, I get a console error that the values in url
are undefined.
I am following this example: http://live.datatables.net/qemodapi/975/edit
This is how a row looks like
{
ActivityPhase: "Complete"
ActivityPhaseDate: "/Date(219999600000)/"
Address: "123 N Main"
AppNumber: 54
Client: "Bob Ben"
EscrowAccountNumber: "123456"
EscrowWithCity: true
HasPayment: false
Hrdbid: null
Id: "a21d627e-97ab-477f-afc1-27c2637f7c05"
Month: 6
Notes: null
Year: 2022
}
CodePudding user response:
Since data is passed into the DataTable as an array of object, data in each row will be represented as an object and not an array. So you should access members of the row (data of each column) any of the object access methods instead of that of an array.
Change this line
var url = `Payment/Set?applicationId=${data[14]}&year=${data[12]}&month=${data[13]}&hasPayment=${data[11]}`;
To this
var url = `Payment/Set?applicationId=${data['AppNumber']}&year=${data['Year']}&month=${data['Month']}&hasPayment=${data['HasPayment']}`;