How to access REST APIs that don't provide a 'data'-array
How to access REST APIs that don't provide a 'data'-array
Hello,
I'm trying to use the datatables editor to access a json api that doesn't respond with an array containing the individual rows in a data array but with an flat array. So it returns:
[
{
"id": 1,
"name": "Model 1"
},
{
"id": 2,
"name": "Model 2"
},
{
"id": 3,
"name": "Model 3"
}
]
instead of
{
"data": [
{
"id": 1,
"name": "Model 1"
},
{
"id": 2,
"name": "Model 2"
},
{
"id": 3,
"name": "Model 3"
}
], [...]
}
Also it requires to POST and PUT with a JSON payload in the format:
{
"name": "Model 4"
}
I used functions for data
in the ajax
definitions in the Editor-construction to modify the data coming out of datatables before it is being sent as a request to my API
$(document).ready(function() {
editor = new $.fn.dataTable.Editor( {
ajax: {
create: {
type: 'POST',
url: 'fake',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: function(d) {
var j
j = d.data[0]
j = JSON.stringify(j);
return j;
}
dataSrc: ''
},
edit: {
type: 'PUT',
url: 'api/models/_id_',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: function(d) {
var j
j = d.data;
j = j[Object.keys(j)[0]];
j = JSON.stringify(j);
return j;
},
dataSrc: ''
},
remove: {
type: 'DELETE',
url: 'api/models/_id_',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: ''
}
},
table: "#example",
idSrc: 'id',
fields: [ {
label: "Name:",
name: "name"
}
]
} );
$('#example').DataTable( {
dom: "Bfrtip",
ajax: {
type: 'GET',
url: 'api/models',
dataSrc: ''
},
columns: [
{ data: "id" },
{ data: "name" }
],
select: true,
buttons: [
{ extend: "create", editor: editor },
{ extend: "edit", editor: editor },
{ extend: "remove", editor: editor }
]
} );
} );
Posting new resources and updating existing ones works fine. But the new resources or the updates are not shown in the actual table. So I have to reload the whole page to check whether the changes were successful, which is quite inconvenient. I traced the issue down to the fact, that the response of API to posting "Model 4"
is:
{
"id": 4,
"name": "Model 4"
}
If I mock the response to be
{
"data": [
"id": 4,
"name": "Model 4"
]
}
the updating works fine. However, changing the API to always respond that way is not possible due to compatibility reasons. Does anybody have a solution for my issue?
Answers
I presume form the above code that the DataTable itself is correctly populated? But its the Editor aspect that is causing issues?
With that assumption, you have to use
submitSuccess
to modify the data that is returned from the server into that which Editor expects.Regards,
Allan