Get data from ajax POST call
Get data from ajax POST call
Hello,
I've problem with DataTable to read data from my ajax call.
Originally I was populating my Table like so:
$.ajax({
type: "POST",
url: 'formularze_dane.php',
data: {login: val1, type: 'user_privileges'},
success: function(result){
$("#testDiv").append(JSON.stringify(result));
const table = document.getElementById("userPrivilegesTableTBody");
$("#userPrivilegesTableTBody").empty();
for (let i = 0; i < result.length; i++) {
let counter = 0;
let row = table.insertRow();
for(key in result[i]){
let val2 = row.insertCell(counter);
val2.innerHTML = result[i][key];
counter++;
}
}
}
});
And everything was working just fine. ButI wanted to try datatables, so I tried:
$('#userPrivilegesTable').DataTable({
ajax: {
type: "POST",
url: 'formularze_dane.php',
data: {login: val1, type: 'user_privileges'}
}
});
As you can see below, table is created, column names are also loaded, but cells values are not

Debugger also say so:
Information about 1 table available
#userPrivilegesTable
Data source: Ajax
Processing mode: Client-side
Draws: 1
Columns: 3
Rows - total: 0
Rows - after search: 0
Display start: 0
Display length: 10
I log object from ajax call into console it's structure below:
[
{"login":"value","system":"value","uprawnienie":"value"},
{"login":"value","system":"value","uprawnienie":"value"},
{"login":"value","system":"value","uprawnienie":"value"}
]
And last, error that it gives:
Uncaught TypeError: Cannot read properties of undefined (reading 'length')
at jquery.dataTables.js:4834:26
at Object.callback [as success] (jquery.dataTables.js:3952:4)
at j (jquery.min.js:2:27295)
at Object.fireWith [as resolveWith] (jquery.min.js:2:28108)
at x (jquery.min.js:4:22061)
at XMLHttpRequest.b (jquery.min.js:4:25980)
This question has accepted answers - jump to:
This discussion has been closed.
Answers
datashouldn't be under the ajax call, it should becolumns.data- please see example here,Colin
You might need to use
ajax.dataSrcto point to the row data. See the second example in the docs and also the Ajax docs.Kevin
You're right. Since I had a problem with reading .json, I've place it into success function, like so:
And I'ts working just fine.