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

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.

Related

pass json data collectio into DataTable

I trying to insert json collection in datatable using jQuery.
This is my code:
function reloadseekers(vacancy){
if (vacancy) {
$.ajax({
url: '/getseekers/' + vacancy,
method: "GET",
dataType: "json",
cache: false,
success: function (data) {
$.each(data.appseekers, function (index) {
$('#evaluated_list_table').dataTable({
"paging": true,
"lengthChange": true,
"searching": true,
"ordering": true,
"info": true,
"autoWidth": true,
"data": data.appseekers,
"columns": [
{ "title": "SSN" },
{ "data": data.appseekers[index].ssn},
{ "title": "Full Name" },
{ "data": data.appseekers[index].first_name + ' '+data.appseekers[index].second_name +' '+data.appseekers[index].middle_name+' '+data.appseekers[index].last_name },
{ "title": "Primary phone" },
{ "data": data.appseekers[index].phone_1},
{ "title": "Secondary phone " },
{ "data": data.appseekers[index].phone_2},
{ "title": "Secondary phone " },
{ "data": data.appseekers[index].evaluation.total_evaluation},
]
});
});
}
}
}
The table empty and without any data,,, the json data is already gotten from the server:
The json data from the server
what is wrong in this code? help please

Pass Parameters through ajax call - ajax url

I am trying to pass value parameter through the ajax call to the controller. It is a date value. I am struggling to find a way to pass parameters through this ajax url. Please help.
function dataTable() {
var value = $("#somedatevalue).val();
$("#thisTable").DataTable({
"processing": true,
"paging": false,
"language": {
processing: "<span class='processing-message'><i class='fa fa-circle-o-notch fa-spin'></i> Processing...</span>"
},
ajax: {
url: $('table#thisTable').data("ajaxurl"),
type: "POST",
datatype: "json",
},
"columns": [
{
"data": "column1",
},
{
"data": "column2",
},
{
"data": "column3",
},
{
"data": "column4",
},
{
"data": "column5",
},
{
"data": "Url",
"render": function (data) {
return '<a class="btn btn-info" href="' + data + '">Select</a>';
}
}
],
"dom": 't<"col-lg-3"l><"col-lg-6"p><"col-lg-3"i>'
});
}
You can pass value as query parameter like http://www.url.com?date="17-02-21"
If you are using php use can get the value as $_GET['date']
If you are using node js, you can get value as req.query.date
Consider the following.
function dataTable() {
$("#thisTable").DataTable({
"processing": true,
"paging": false,
"language": {
processing: "<span class='processing-message'><i class='fa fa-circle-o-notch fa-spin'></i> Processing...</span>"
},
"ajax": {
"url": $('table#thisTable').data("ajaxurl"),
"type": "POST",
"data": { "someDate": $("#somedatevalue").val() },
"datatype": "json"
},
"columns": [
{
"data": "column1",
},
{
"data": "column2",
},
{
"data": "column3",
},
{
"data": "column4",
},
{
"data": "column5",
},
{
"data": "Url",
"render": function (data) {
return '<a class="btn btn-info" href="' + data + '">Select</a>';
}
}
],
"dom": 't<"col-lg-3"l><"col-lg-6"p><"col-lg-3"i>'
});
}
First you must address the Typo in your jQuery Selector. Then you can adjust your Ajax parameters to include a data.
See more here: https://datatables.net/reference/option/ajax.data
In principle it operates in exactly the same way as jQuery's $.ajax.data property, in that it can be given as an object with parameters and values to submit, but DataTables extends this by also providing it with the ability to be a function, to allow the data to be re-evaluated upon each Ajax request (see above).

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"
}]
});

JQuery Datatable initialization

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?

dataTables not formatted on Page refresh

I have recently started working on datatables and have so far with help from some genues in the community been able to get to a point in my code so far. The issue I have is
1: when I refresh my browser, because it takes few seconds to display the datas, the table headings all appears to be merged together
2: Also I am using datatables v1.10.x and i tried using the new APIs like alertTable.clear().draw(); instead of dataTable().fnClearTable(); but I am getting alertTable.clear is not a function. I noticed changing from dataTable to DataTable seems to have an effect but it still does not work.
Any help will be much appreciated as I am still new to this plugin.
Code:
<script type="text/javascript" charset="utf-8">
var red=0;
var orange=0;
$(document).ready(function (){
setInterval (function(){
$.getJSON("ajax/maint1_json.txt", function (pcheckdata){
<!-- ------------------- Extract all Alerts ---------------------- -->
if (!$.fn.DataTable.isDataTable('#alert-table')) {
$('#alert-table').dataTable({
"bInfo": false,
"bJQueryUI": true,
"bPaginate": false,
"bLengthChange": false,
"bFilter": false,
"data": pcheckdata.alerts,
"aaSorting": [[ 3, "desc" ]],
"columns": [
{ "mData": "source" },
{ "mData": "host" },
{ "mData": "description" },
{ "mData": "value" }
],
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
if ( aData.value == "5" )
{
$('td', nRow).css('background-color', 'Red');
red++;
}
else if ( aData.value == "4" )
{
$('td', nRow).css('background-color', 'Orange');
orange++;
}
},
"aoColumnDefs": [
{
"targets": [ 0 ],
"visible": false,
"searchable": false
},
{
"targets": [ 3 ],
"mRender": function( data, type, full ) {
if (data == "0") {
return '<input class="button" type="button" id="ack-action" value="Acknowledge Alert" onclick="<-- call a function to modify value -->;">';
}
return data;
}
}
],
<-- if json value is null or empty -->
'fnServerData': function (sSource, aoData, fnCallback) {
$.ajax ({
'dataType': 'json',
'type': 'POST',
'url': sSource,
'data': aoData,
'success': fnCallback
});
},
"fnDrawCallback": function ( oSettings ) {
$('.alertcount-red').empty().append(red);
$('.alertcount-orange').empty().append(orange);
red=0;
orange=0;
}
});
} else
{
$('#alert-table').dataTable().fnClearTable();
$('#alert-table').dataTable().fnAddData(pcheckdata.alerts);
$('#alert-table').dataTable().fnAdjustColumnSizing();
}
if (!$.fn.DataTable.isDataTable('#error-table')) {
<!-- ------------------- Extract all Errors ---------------------- -->
$('#error-table').dataTable({
"bInfo": false,
"bJQueryUI": true,
"bPaginate": false,
"bLengthChange": false,
"bFilter": false,
"data": pcheckdata.errors,
"columns": [
{ data: 'host' },
{ data: 'description' }
],
'fnServerData': function (sSource, aoData, fnCallback) {
$.ajax ({
'dataType': 'json',
'type': 'POST',
'url': sSource,
'data': aoData,
'success': fnCallback
});
}
});
} else
{
$('#error-table').dataTable().fnClearTable();
$('#error-table').dataTable().fnAddData(pcheckdata.alerts);
$('#error-table').dataTable().fnAdjustColumnSizing();
}
});
}, 10000);
});
</script>

Categories

Resources