I have a backend server that is expecting a response in the form of a boolean. I've been following this example exactly as what is posted in this demo example:
https://editor.datatables.net/examples/api/checkbox.html
I have the following field on the editor:
{
label: "Active",
name: "active",
type: "checkbox",
options: [
{ label: '', value: true }
]
}
Executing the following code:
_editor
.edit($(this).closest('tr'), false)
.set('active', true)
.submit();
Send the following value to the server:
"[\r\n 1\r\n]"
Setting the field to false:
_editor
.edit($(this).closest('tr'), false)
.set('active', false)
.submit();
Send the following value to the server:
"[]"
These results aren't what I'd expect when setting a checkbox value with a boolean type. Why can't I just receive a simple "true" or "false" value? As this complicates my code on the backend.
Then I investigated what was going on:
var _editor = new $.fn.dataTable.Editor({
ajax: {
url: '/api/Test',
data: function (d) {
var id;
switch (d.action) {
case "create":
id = 0;
break;
case "edit":
case "remove":
id = d.data[Object.keys(d.data)[0]].ID;
break;
}
console.log(d.data[id].active); //weird results
return JSON.stringify(d);
},
....
}
});
In the console log, I found out that if the value is true, then d.data[id].active is an array with one index, with the value true. And if the value is false, then d.data[id].active is undefined.
Is there a reason why this logic exists like that? It took me forever to find out what was going on and why my server kept blowing up. To remedy this, in the ajax code I did this:
var retVal = false;
if (d.data[id].active.length > 0) {
retVal = d.data[id].active[0]
}
d.data[id].active = retVal;
return JSON.stringify(d);