You have two ajax calls (the jQuery call and then the DataTables call), where only one ajax call is needed.
If you want to fetch your data using the jQuery ajax call, you can pass that data to DataTables using the DataTables data
option. To do this, you need to replace the DataTables ajax
section with the data
option.
Because I do not have your JSON provider for testing, I will use the publicly available "jsonplaceholder" URL:
$(document).ready(function() {
$.ajax({
method: "GET",
url: "https://jsonplaceholder.typicode.com/posts",
//data: '{}',
//contenttype: "application/json; charset=utf-8",
//datatype: "json",
success: onsuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
});
function onsuccess(response) {
//console.log(response);
$('#example').DataTable( {
"data": response, // this passes your data to DataTables
"columns": [
{ "title": "User ID", "data": "userId" },
{ "title": "ID", "data": "id" },
{ "title": "Title", "data": "title" }
]
} );
}
Note that the following three lines...
data: '{}',
contenttype: "application/json; charset=utf-8",
datatype: "json",
...are not strictly required for my demo to work.
If you prefer, you can simplify the above approach by using only the DataTables ajax call. In this case you need to use dataSrc
in the ajax
section of your DataTable definition:
$(document).ready(function() {
var table = $('#example').DataTable( {
ajax: {
method: "GET",
url: "https://jsonplaceholder.typicode.com/posts",
dataSrc: ""
},
"columns": [
{ "title": "User ID", "data": "userId" },
{ "title": "ID", "data": "id" },
{ "title": "Title", "data": "title" }
]
} );
} );
This gives the same result as my first example.
Minor point: you have a small typo here in your question:
"datasrc": function (responce)
It should be dataSrc
not datasrc
.