I can successfully fill my datatable with ajax call, but then I don't know how to parse JSON that is received by datatable with this ajax call.
Here is my JavaScript code, that makes ajax call to the server and fills my datatable correctly:
$('#transactions').DataTable({
"processing": true,
"ajax": {
"url": "/transactions
},
"columns": [
{ "data": "car"},
{ "data": "card_number"},
{ "data": "invoice"},
{ "data": "status"}
]
});
This is the JSON object returned from the server:
{
"data": [
{
"car": 190,
"card_number": "6395637",
"invoice": 200,
"status": "success"
},
{
"car": 191,
"card_number": "9473650",
"invoice": 180,
"status": "success"
}
],
"balance": 7300
}
As you can see, the data parameter of the returned JSON object is used by the datatables function to fill by datatables, and now I want to parse the balance parameter, but I can't. How can i achieve this?
Something like this:
$('#transactions').dataTable({
"ajax" : {
"url" : "/transactions",
"dataSrc" : function (json) {
// manipulate your data (json)
...
// return the data that DataTables is to use to draw the table
return json.data;
}
}
});
Docs: https://datatables.net/reference/option/ajax.dataSrc
Don't use the url feature of DataTable, make the Ajax call yourself
$.getJSON('/transactions', function(response) {
$('#transactions').dataTable({
processing: true,
data: response.data,
columns: [
{ data: "car"},
{ data: "card_number"},
{ data: "invoice"},
{ data: "status"}
]
});
window.someGlobalOrWhatever = response.balance
});
Since DataTables 1.10, you may use the ajax.json() function: https://datatables.net/reference/api/ajax.json()
I have implemented it in the example code below.
$( document ).ready(function() {
$('#search-form').submit(function(e) {
e.preventDefault();
var table = $('#location-table').DataTable({
destroy: true,
ajax: "/locations.json",
columns: [
{ "data": "code" },
{ "data": "status" },
{ "data": "name" },
{ "data": "region" },
{ "data": "address" },
{ "data": "city" },
{ "data": "state" },
{ "data": "zip" },
{ "data": "phone_number" },
]
})
table.on( 'xhr', function () {
var json = table.ajax.json();
$('#totals').text(json.totals)
});
})
});
NOTE for this to work you must initialize the datatable with $('#location-table').DataTable() and not $('#location-table').dataTable (the difference being the capitalized D)
Related
Trying to pass some parameters in JQuery Datatables, its working fine on init.
But when I try to refresh the datatable the values are received as empty on controller side.
Here is the code:
$("#SearchResultsTable").DataTable({
"processing": true,
"serverSide": true,
"bLengthChange": false,
"filter": false,
"pageLength": #Model.PageSize,
"orderMulti": false,
"ajax": {
"url": "/Request/SearchRequest",
"type": "POST",
"datatype": "json",
"data": {
"Date_To": document.getElementById("Date_To").value,
"Date_From": document.getElementById("Date_From").value
}
},
"columns": [
{ "data": "ABC", "name": "ABC", "autoWidth": true },
{ "data": "DEF", "name": "DEF", "autoWidth": true }
]
});
Refresh Datatable:
$("#Search_Btn").click(function () {
$("#SearchResultsTable").DataTable().clear();
$("#SearchResultsTable").DataTable().draw();
});
Also tried:
$("#Search_Btn").click(function () {
var table = $('#SearchResultsTable').DataTable();
table.ajax.reload();
});
I would like to refresh the table in such a way the updated vales of 'Date_To' & 'Date_From' are available on controller side.
You will need to pass the parameters via jquery datatable like below:
"data": function (data) {
data.Date_To = document.getElementById("Date_To").value;
data.Date_From = document.getElementById("Date_From").value;
}
Please take a look at the following tutorial for more details
https://www.codeproject.com/Articles/1170086/Grid-with-Server-Side-Advanced-Search-using-JQuery
The thing is that i am trying to fill a datatable like this
$('#example tbody').on('click', 'tr', function () {
var data = table.row( this ).data();
alert( 'You clicked on '+data.name+'\'s row' );
$.ajax({
url: data.url,
dataType: 'json',
success: function(json){
console.log(json)
tableDos.rows.add([json]).draw();
}
});
} );
What this does is that when someone selects a row from another datatable that its already filled, it is going to extract the URL of the selected JSON from the row (The JSON comes from SWAPI.CO API) and passed it through to fill another datatable like this.
var tableDos = $('#exampleDos').DataTable({
"columns": [{
"title": "Films",
"data": "films",
render: function (data, type, row, meta) {
var currentCell = $("#exampleDos").DataTable().cells({"row":meta.row, "column":meta.col}).nodes(0);
// $.each(data, function (i, item){
$.ajax({
url: data[0],
success: function(json){
console.log(json)
$(currentCell).text(json.title);
}
});
// })
return null;
}
},
{
"title": "Vehicles",
"data": "vehicles"
},
{
"title": "Starships",
"data": "starships"
}
]
});
The tricky part comes here, what this table is receiving is coming from this JSON
{
"name": "Luke Skywalker",
"height": "172",
"mass": "77",
"hair_color": "blond",
"skin_color": "fair",
"eye_color": "blue",
"birth_year": "19BBY",
"gender": "male",
"homeworld": "https://swapi.co/api/planets/1/",
"films": [
"https://swapi.co/api/films/2/",
"https://swapi.co/api/films/6/",
"https://swapi.co/api/films/3/",
"https://swapi.co/api/films/1/",
"https://swapi.co/api/films/7/"
],
"species": [
"https://swapi.co/api/species/1/"
],
"vehicles": [
"https://swapi.co/api/vehicles/14/",
"https://swapi.co/api/vehicles/30/"
],
"starships": [
"https://swapi.co/api/starships/12/",
"https://swapi.co/api/starships/22/"
],
"created": "2014-12-09T13:50:51.644000Z",
"edited": "2014-12-20T21:17:56.891000Z",
"url": "https://swapi.co/api/people/1/"
}
So my table as you can see is receiving films, vehicles and starships in the form of an array and URL so i have to do another AJAX call as you can see in the table from for example "films" so i in the AJAX url i have to iterate through the films ARRAY but it automatically iterates without using loops or each and i cant make it work. It seems confusing but check it out for yourselves.
https://jsfiddle.net/um8tmgq2/2/
I am using Datatable to render a table. The code is -
var nextPage;
$(document).ready(function() {
$('#table').DataTable( {
"processing": true,
"ordering": false,
"serverSide": true,
"sorting":false,
"paging": true,
"pageLength":20,
"lengthChange" :false,
"pagingType":"simple",
"ajax": function (data, callback, settings) {
data.nextPage=document.getElementById("nextPage").value
$.ajax({url: "get/list", data: data, success: function(result){
document.getElementById("nextPage").value=result.nextPage;
callback(result);
}});
},
"columns": [
{ "data": "first_name" },
{ "data": "title" },
{ "data": "first_name" },
{ "data": "first_name" },
{ "data": "first_name" },
{ "data": "first_name" },
{ "data": "work_email" }
]
});
});
The first page loads fine when I open the page, but the second page keeps on loading. The /get/list API call succeeds for the second page but the data is not rendered on the browser and loading icon keeps on rotating.
I have used server-side processing data table.
Here is my datatable configuration:
var table = $("#job-table").DataTable({
"ajax": {
"url": "<?php echo url('/getJobs');?>",
"type": "POST",
"data": function (d) {
d.connection = connectionArray,
d.company = companyArray,
d.type = typeArray
}
},
"processing": true,
"serverSide": true,
"columns": [
{ "data": "id" },
{ "data": "job_id" },
{ "data": "type" },
{ "data": "connection_id" },
{ "data": "company_id" },
{ "data": "message" },
{ "data": "total_completion_time" },
{ "data": "date" },
{ "data": "start_time" },
{ "data": "end_time" },
{ "data": "error_time" }
],
"info": false,
"searching": false,
"bLengthChange": false
});
In this datatable ajax response I have passed some another data which I am gonna use to set custom label value.
Right now, I am using same ajax call to set label value. There are two calls one is of datatable and another call for setting label. Both time I am calling same API. but want to know how can I avoid second ajax call?
Is there any way to use data-table ajax call response to set custom label value?
I do something similar. I used the dataFilter callback to handle it.
so given HTML:
<input id="txtOne"/>
<input id="txtTwo"/>
<table id="job-table" class="display"></table>
Serverside code is returning a JSON Serialized object that looks like:
{ ValueOne: "some data",
ValueTwo: "Some more data",
data: [array of data for the table] }
My table definition looks like (notice the dataFilter section):
var table = $("#job-table").DataTable({
"ajax": {
"url": "<?php echo url('/getJobs');?>",
"type": "POST",
"data": function (d) {
d.connection = connectionArray,
d.company = companyArray,
d.type = typeArray
},
// I added this section. It is called before the success callback
// You will have to figure out your parsing at this point because
// each configuration is different so I just put how mine is.
dataFilter: function(response){
var temp = JSON.parse(response);
$("#txtOne").val(temp.ValueOne);
$("#txtTwo").val(temp.ValueTwo);
return response;
}
},
"processing": true,
"serverSide": true,
"columns": [
{ "data": "id" },
{ "data": "job_id" },
{ "data": "type" },
{ "data": "connection_id" },
{ "data": "company_id" },
{ "data": "message" },
{ "data": "total_completion_time" },
{ "data": "date" },
{ "data": "start_time" },
{ "data": "end_time" },
{ "data": "error_time" }
],
"info": false,
"searching": false,
"bLengthChange": false
});
When loading a jQuery DataTable, I have the code shown below. How do I pass additional parameters to the AJAX call? The fnServerParams callback suggested in the questions and answers below does not work. That is, naively using aodata.push() results in "push is undefined" (because, indeed, aodata is not an array). So what's the correct way to do this?
Related questions:
Datatables serverside. Send extra parameters asynchronously
Understanding fnServerData in Datatables
Code:
self.dataTable = self.dataTableContainer.DataTable({
"autoWidth": false,
"bSort": false,
"displayStart": 0,
"paging": false,
"lengthChange": false,
"processing": true,
"serverSide": true,
"dom": "<'dataTables_header dashboard_alert_history__alertHeader'i>",
"ajax": {
url: getDataUri,
error: onError,
cache: false,
"fnDrawCallback": onTableDrawn,
},
"fnDrawCallback": onTableDrawn,
"language": {
"info": resources.alarmHistory,
"infoEmpty": resources.alarmHistory,
"infoFiltered": ''
},
"columns": [
{
"data": "timestamp",
"mRender": function (data) {
return IoTApp.Helpers.Dates.localizeDate(data, 'L LTS');
},
"name": "timestamp"
},
{
"data": "deviceId",
"mRender": function (data) {
return htmlEncode(data);
},
"name": "deviceId"
},
{
"data": "ruleOutput",
"mRender": function (data) {
return htmlEncode(data);
},
"name": "ruleOutput"
},
{
"data": "value",
"mRender": function (data) {
return htmlEncode(IoTApp.Helpers.Numbers.localizeFromInvariant(data));
},
"name": "value"
},
],
"columnDefs": [
{
"targets": [0, 1, 2, 3],
"className": 'table_alertHistory_issueType',
"width": "20%"
}
],
});
I neglected to RTFM. The fnServerParams callback is now legacy for versions 1.9 and earlier. In the latest version of DataTables, you leverage the ajax data parameter as described in the DataTables documentation. In the example below, appending mykey to the d object will do the trick:
$(document).ready(function() {
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "scripts/server_processing.php",
"data": function ( d ) {
d.myKey = "myValue";
// d.custom = $('#myInput').val();
// etc
}
}
} );
} );