JQuery Datatable initialization - javascript

I'm getting this error while trying to supply JSON into my DataTable:
DataTables warning: table id=myTable - Requested unknown parameter 'a' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
This is what my JSON looks like:
[{
"a": "asdsaddas",
"b": "asdasda",
"c": "0000000001",
"d": "name"
}]
When user clicks button I'm generating and showing the table with an AJAX callback:
$('#find_button').click(function() {
event.preventDefault();
if (validateAll()) {
$("#myTable").DataTable({
"lengthChange": false,
"pageLength": 20,
autoWidth: false,
serverSide: true,
processing: true,
"dataSrc": "",
"ajax": function(data, callback, settings) {
var $form = $("#my_form_id");
var jsonData = getFormData($form, data.start, data.length);
var request = $.ajax({
type: "POST",
url: "api",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(jsonData),
dataType: "json"
});
request.then(function(response) {
console.log(JSON.stringify(response.data));
callback({
data: [JSON.stringify(response.data)],
recordsTotal: response.total,
recordsFiltered: response.total
})
}, failCallback);
},
columns: [{
"data": "a"
}, {
"data": "b"
}, {
"data": "c"
}, {
"data": "d"
}],
filter: false,
info: false,
ordering: false
});
$('#htmlTable').show();
}
});
I've read a lot of related questions with same bug, but still cannot make it work in my case. Maybe there is problem that DataTable is initialized before it gets response from server?

Related

Using JSON data to filll "columns" in datatable

I am getting JSON data via AJAX and my data are in a result object. The fields of which can be accessed as in success: function(result)
result.map.count[0].name
result.map.count[0].count
I would like to show name and count as two columns of my datatable.
My ajax request is written as
table = $('#_table').dataTable({
searching: false,
paging: true,
ajax: function (data, callback, settings) {
$.ajax({
type: "post",
url: '/test/getvalues',
dataType: "json",
success: function (result) {
I am able to get data as "result" here
result.map.count[0].name
result.map.count[0].count
}
});
},
columns: []
})
what should I put in columns[] to show these fields?
columns: []
In your datatable configuration,add the following
data: [[result.map.count.name,result.map.count.count]], // make it as array of values
columns: [
{
"sClass": "center",
"name": "Name"
},
{
"sClass": "center",
"name": "Count"
},
]
Please check here for more details
https://datatables.net/examples/data_sources/js_array.html
I've found my answer.
I need to write a callback function that returns the data (array) which is found from my object.
Code:
table = $('#_table').dataTable({
searching: false,
paging: true,
ajax: function (data, callback, settings) {
$.ajax({
type: "post",
url: '/test/getvalues',
dataType: "json",
success: function (result) {
var dataToUse = {};
dataToUse.data = result.map.count;
callback(dataToUse);
}
});
},
columns: [
"data": "name",
"data": "count"
]
})
}
Please try this.
table = $('#_table').dataTable({
searching: false,
paging: true,
ajax: function (data, callback, settings) {
$.ajax({
type: "post",
url: '/test/getvalues',
dataType: "json",
success: function (result) {
callback(result.map.count);
}
});
},
// Columns
columns: [{
title: "Name",
name: "name",
}, {
title: "Count",
name: "count"
}]
});

How to seed data from AJAX response when Datatables is already initialized?

I have a mix of Select2JS and Datatables and here is the code involved in the issue:
$(function() {
var form_id = $('#form_id'),
form_results = $('#form_results');
form_results.DataTable();
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'json',
url: '/ajax/forms/get/',
data: JSON.stringify({
form_id: null,
show_archived: !!$('#show_archived').is(':checked'),
get_first: false,
format: 'select2',
}),
cache: false,
success: function(data) {
form_id.removeAttr('disabled');
form_id.select2({
data: data,
closeOnSelect: true,
matcher,
sorter,
}).on('select2:select', function(e) {
var selected_element = $(e.currentTarget);
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'json',
url: '/ajax/manage_forms/getFormData/',
data: JSON.stringify({
form_id: selected_element.val(),
get_first: true,
}),
cache: false,
success: function(response) {
form_results.DataTable({
data: response.data,
retrieve: true,
stateSave: true,
responsive: true,
columnDefs: [
{
className: 'select-checkbox',
orderable: false,
searchable: false,
targets: 0,
},
],
select: {
style: 'multiple',
selector: 'td:first-child',
},
});
},
error: function(xhr, ajaxOptions, thrownError) {
console.error(xhr.responseText);
},
});
});
},
error: function(xhr, ajaxOptions, thrownError) {
console.error(xhr.responseText);
},
});
});
On the PHP side there is a function building the data and send it back to the browser:
public function getFormData()
{
$inputJSON = file_get_contents('php://input');
$outputJSON = json_decode($inputJSON, true);
$arguments = array(
'Id' => $outputJSON['form_id'],
'FormName' => null,
'FormFileName' => null,
'FormTypeId' => 1
);
$form = $this->forms_model->get($arguments, $outputJSON['get_first'], self::$folders);
$result[] = array(
'',
'DT_RowId' => $form->Id,
$form->FormName,
$form->FaxNumber,
end(explode('/', $form->form_filepath))
);
return $this->output->set_content_type('application/json')->set_output(json_encode(array('data' => $result)));
}
The result from the above function looks like:
{
"data" : [
{
"0" : "",
"DT_RowId" : 3387,
"1" : "form",
"2" : "8772399284",
"3" : "form1.pdf"
}
]
}
For some reason the table is showing all the time "No data available in table" and I can't find where is the issue, can any find out what is wrong in my code?
I have spent the last two hours trying to figure this out but I can't.
Updates:
#charlietfl: the following didn't work at first complaining about the k not being defined so I modified a little bit however it didn't do the trick
response.data.map(function(k, o) {
return Object.keys(k).map(function(k) { return o[k];});
});
#CFP Support: your solution is not working either for some reason the table doesn't get updated with data.
In both cases I am not getting any Javascript error or nothing weird in the console it just does not work.
You need to add the "columns" and define them.
...stuff...
columnDefs: [
{
className: 'select-checkbox',
orderable: false,
searchable: false,
targets: 0,
},
],
columns: [
{data: "0"},
{data: "DT_RowId"},
{data: "1"},
{data: "2"},
{data: "3"}
], ....etc...
This tells the table what column to match with the incoming data (so you will need a table with 5 columns in the HTML - or build it with JS {not sure what you are using, but if you need help...}
This should get you past the immediate issue though.
EDIT: JSFiddle - https://jsfiddle.net/CFPSupport/5utwh4v3/6/
EDIT2: I see the issue - you are initializing then wanting to put more data.... OK.....
You should get the data IN the datatable init, not init+AJAX.... https://datatables.net/reference/option/ajax

Is it possible to use Ajax success result to populate jQuery DataTable

I would like to declare my jQuery datatable without initially populating it and later when calling Ajax functions, I would like to take the results and use that as the data source for my data table, right now I am making multiple Ajax calls for the same purpose and I would like to eliminate this if possible.
$.ajax({
type: "GET",
url: "/Receiving/GetUnorderedParts",
datatype: "html",
data: { "id": button.attr("data-ponumber") },
success: function(data) {
var orderButton = $(".js-Order");
orderButton.removeClass("invisible");
tbl = $("#UnorderedDetail")
.DataTable({
"destroy": true,
"searching": false,
"ordering": false,
"lengthChange": false,
"pagingType": "full_numbers",
"paging": true,
"lengthMenu": [10, 25, 50, 75, 100],
ajax: {
url: "/Receiving/GetUnorderedParts",
data: { "id": button.attr("data-ponumber") },
datasrc: ""
},
"columnDefs": [
{
targets: -1,
className: 'dt-body-center'
}
],
columns: [
{
data: "Description"
},
{
data: "VendorPartNumber"
},
{
data: "Quantity"
},
{
data: "CartID",
render: function(data) {
return "<button class='btn btn-danger js-delete' data-cart-id=" +
data +
">Delete</button>";
}
}
] //EOColumns
}); //EODataTable
} //EOSuccess
}); //EOInnerAjax
You can call a function to build the data table on success something like:
$.ajax({
type: "GET",
url: "/Receiving/GetUnorderedParts",
datatype: "html",
data: { "id": button.attr("data-ponumber") },
success: function(data) {
var orderButton = $(".js-Order");
orderButton.removeClass("invisible");
createTable(data);
}
});
and the function can take in the array of objects and create a data table:
function createTable(dataSet)
{
$('#example').DataTable({
data: dataSet,
"aoColumns": [{
"sTitle": "Description",
"mData": "Description"
}, {
"sTitle": "VendorPartNumber",
"mData": "VendorPartNumber"
}, {
"sTitle": "Quantity",
"mData": "Quantity"
}, {
"sTitle": "CartID",
"mData": "CartID",
"mRender": function(data) {
return "<button class='btn btn-danger js-delete' data-cart- id=" + data + ">Delete</button>";
}}]
});
}
Check out a working example . It takes in an array of objects and create a datatable.

Update ajax data programatically for jQuery datatables

I have a jQuery datatable with an ajax datasource defined like so:
var selected_ids = [];
selected = $('#selected_members').dataTable( {
"ajax": {
'type': 'GET',
'url': "{!! route('admin.members.included_datatables') !!}",
'data': {
'member_ids' : JSON.stringify(selected_ids)
},
},
"processing": true,
"serverSide": true,
"columns": [
null,
null,
null,
null,
null,
{"searchable": false, "orderable": false}
]
});
$('#available_members').on('click', '.select', function(e) {
e.preventDefault();
member_id = $(this).data('member-id');
selected_ids.push(member_id);
selected.api().ajax.reload();
});
As you can see I am updating the contents of selected_ids manually and I want to then refresh the datatable. This is working except that when the datatable reloads and does the ajax call the member_ids parameter that it passes to the server is still empty. Do I have to update the data property of the ajax call manually before reloading the table and if so how do I do that?
I fixed it I used a closure for the data attribute instead like so:
selected = $('#selected_members').dataTable( {
"ajax": {
'type': 'GET',
'url': "{!! route('admin.members.included_datatables') !!}",
'data': function ( d ) {
d.member_ids = selected_ids;
return d;
}
},
"processing": true,
"serverSide": true,
"columns": [
null,
null,
null,
null,
null,
{"searchable": false, "orderable": false}
]
});

How to send form data along with jQuery DataTables data in server-side processing mode

I am trying to post form data without success and data couldn't be loaded.
How can I pass all form data with array and single textbox, combobox, etc. to fnServerdata?
table_obj = $('#group-table').dataTable({
"sAjaxSource": "URL Goes here",
fnServerData: function(sSource, aoData, fnCallback,oSettings) {
oSettings.jqXHR = $.ajax( {
"dataType": 'json',
"type": "POST",
"url": sSource+'?'+$.param(aoData),
"data": $("#frm").serializeArray(),
"success": fnCallback
} );
},
aaSorting: [[ 1, "desc" ]],
bProcessing: true,
bServerSide: true,
processing : true,
columnDefs: [{
'targets': 0,
'searchable':false,
'orderable':false,
'className': 'dt-body-center',
'render': function (data, type, full, meta){
return '<label><input type="checkbox" name="user_id[]" value="' + $('<div/>').text(data).html() + '"></label>';
}
}],
rowCallback: function(row, data, dataIndex){
// If row ID is in list of selected row IDs
if($.inArray(data[0], rows_selected) !== -1){
$(row).find('input[type="checkbox"]').prop('checked', true);
$(row).addClass('selected');
}
},
iDisplayLength: '50',
});
If you want to format the POST data, you can also format the form data using jquery .each() function. Let me use the answer above using solution #1 but with jquery .each() to format the data.
$('table').DataTable({
"ajax": {
"url": "URL HERE",
"type": "POST",
"data": function(d) {
var frm_data = $('form').serializeArray();
$.each(frm_data, function(key, val) {
d[val.name] = val.value;
});
}
}
});
Then you can just access that in PHP like:
var $data = $_POST['name'];
SOLUTION 1
Replace this:
$('#group-table').dataTable({
"sAjaxSource": "URL Goes here",
fnServerData: function(sSource, aoData, fnCallback,oSettings) {
oSettings.jqXHR = $.ajax( {
"dataType": 'json',
"type": "POST",
"url": sSource+'?'+$.param(aoData),
"data": $("#frm").serializeArray(),
"success": fnCallback
} );
},
with:
$('#group-table').dataTable({
"ajax": {
"url": "URL Goes here",
"type": "POST",
"data": function(d){
d.form = $("#frm").serializeArray();
}
},
Your form data will be in form parameter as an array of objects with parameters name and value, below is JSON representation:
"form": [{"name":"param1","value":"val1"},{"name":"param2","value":"val2"}]
SOLUTION 2
If you want to have form data as name/value pairs, see this jsFiddle for an example of alternative solution.
NOTES
There are checkboxes in your data table. Solution above will not work for form elements in the data table, because DataTable removes non-visible nodes from DOM.
How about this?
$('#group-table').DataTable( {
"processing": true,
"serverSide": true,
"bDestroy": true,
"bJQueryUI": true,
"ajax": {
"url": "url here",
"type": "POST",
"data": {
store: $('#store').val(),
month: $('#m').val(),
year: $('#y').val(),
status: $('#status').val(),
},
}
} );
then you can access the sample data above through PHP using this.
$_POST['store']
$_POST['month']
$_POST['year']
$_POST['status]
Hope that helps.

Categories

Resources