How to update JQuery DataTables from Ajax Call [duplicate] - javascript

I am using plugin jQuery datatables and load my data which I have loaded in DOM at the bottom of page and initiates plugin in this way:
var myData = [
{
"id": 1,
"first_name": "John",
"last_name": "Doe"
}
];
$('#table').dataTable({
data: myData
columns: [
{ data: 'id' },
{ data: 'first_name' },
{ data: 'last_name' }
]
});
Now. after performing some action I want to get new data using ajax (but not ajax option build in datatables - don't get me wrong!) and update the table with these data. How can i do that using datatables API? The documentation is very confusing and I can not find a solution. Any help will be very much appreciated. Thanks.

SOLUTION: (Notice: this solution is for datatables version 1.10.4 (at the moment) not legacy version).
CLARIFICATION Per the API documentation (1.10.15), the API can be accessed three ways:
The modern definition of DataTables (upper camel case):
var datatable = $( selector ).DataTable();
The legacy definition of DataTables (lower camel case):
var datatable = $( selector ).dataTable().api();
Using the new syntax.
var datatable = new $.fn.dataTable.Api( selector );
Then load the data like so:
$.get('myUrl', function(newDataArray) {
datatable.clear();
datatable.rows.add(newDataArray);
datatable.draw();
});
Use draw(false) to stay on the same page after the data update.
API references:
https://datatables.net/reference/api/clear()
https://datatables.net/reference/api/rows.add()
https://datatables.net/reference/api/draw()

You can use:
$('#table').dataTable().fnClearTable();
$('#table').dataTable().fnAddData(myData2);
Jsfiddle
Update. And yes current documentation is not so good but if you are okay using older versions you can refer legacy documentation.

You need to destroy old data-table instance and then re-initialize data-table
First Check if data-table instance exist by using $.fn.dataTable.isDataTable
if exist then destroy it and then create new instance like this
if ($.fn.dataTable.isDataTable('#dataTableExample')) {
$('#dataTableExample').DataTable().destroy();
}
$('#dataTableExample').DataTable({
responsive: true,
destroy: true
});

Here is solution for legacy datatable 1.9.4
var myData = [
{
"id": 1,
"first_name": "Andy",
"last_name": "Anderson"
}
];
var myData2 = [
{
"id": 2,
"first_name": "Bob",
"last_name": "Benson"
}
];
$('#table').dataTable({
// data: myData,
aoColumns: [
{ mData: 'id' },
{ mData: 'first_name' },
{ mData: 'last_name' }
]
});
$('#table').dataTable().fnClearTable();
$('#table').dataTable().fnAddData(myData2);

In my case, I am not using the built in ajax api to feed Json to the table (this is due to some formatting that was rather difficult to implement inside the datatable's render callback).
My solution was to create the variable in the outer scope of the onload functions and the function that handles the data refresh (var table = null, for example).
Then I instantiate my table in the on load method
$(function () {
//.... some code here
table = $("#detailReportTable").DataTable();
.... more code here
});
and finally, in the function that handles the refresh, i invoke the clear() and destroy() method, fetch the data into the html table, and re-instantiate the datatable, as such:
function getOrderDetail() {
table.clear();
table.destroy();
...
$.ajax({
//.....api call here
});
....
table = $("#detailReportTable").DataTable();
}
I hope someone finds this useful!

Related

Get data in json using javascript and datatables

I have a javascript as below, which can fetch the data from backed in json format. But How can i pass it to another function , i.e datatables to populate it
<script>
var returndata;
$.getJSON("/api/dashboard_data/", success);
function success(data) {
returndata = data;
window.alert(returndata);
return returndata;
// do something with data, which is an object
}
$(document).ready(function() {
$('#example').DataTable( {
data: returndata,
columns: [
{ title: "Action" },
{ title: "Input" },
{ title: "State" },
{ title: "Completed" },
{ title: "Project" },
]
} );
} );
</script>
In above code in window.alert(returndata), i get the json data which has been returned from backed.
But the same variable "returndata" when i use it in function ready it is empty. How can i get it in ready function.
You are calling two asynchronous functions here. $.getJSON() and $(document).ready(). It looks that ready() is faster than getJSON() which means returndata is empty when you try to fill your data table.
Try this to make sure you have always the correct order:
<script>
$(document).ready(function() {
$.getJSON("/api/dashboard_data/", function(returndata) {
$('#example').DataTable( {
data: returndata,
columns: [
{ title: "Action" },
{ title: "Input" },
{ title: "State" },
{ title: "Completed" },
{ title: "Project" },
]
});
});
});
</script>
Firstly, which jQuery plugin are you using for DataTables? Is it this one? The first thing I would do would be to put everything inside the $document.ready() as the documentation demonstrates. This ensures that all your code executes after the DOM is ready. Let me know what happens after that.
Also this part of the documentation could help if you are using the DataTables API. It could be as simple as a misspelling depending on what you're trying to do as quoted from the docs here:
The result from each is an instance of the DataTables API object which has the tables found by the selector in its context. It is important to note the difference between $( selector ).DataTable() and $( selector ).dataTable(). The former returns a DataTables API instance, while the latter returns a jQuery object.
I know this is not a good solution, just a hack. You can use window.setInterval or window.setTimeout function to check for data and execute the required function. Don't forget to clear the interval.
Follow the Datatables documentation: https://datatables.net/examples/server_side/simple.html
You'll have to do something like this:
$('#example').DataTable({
"processing": true,
"serverSide": true,
"ajax": _getData(),
"columns": [
{title: "Action"},
{title: "Input"},
{title: "State"},
{title: "Completed"},
{title: "Project"}
]
});
function _getData(data, callback) {
$.getJSON("/api/dashboard_data/", success);
function success(data) {
// you'll probably want to get recordsTotal & recordsFiltered from your server
callback({
recordsTotal: 57,
recordsFiltered: 57,
data: data
})
}
}
I haven't tested this code, but this should guide you in the right direction :)

How to better define JQuery DataTables column rendering?

We use JQuery DataTables extensively. I am now switching all the app tables to AJAX data source to better support search and to render tables faster.
The problem I am having is how to define data rendering inside my table columns. I do not render only data in the column but I need to have some additional markup in some columns (like <span class="label">data</span> or links, etc.).
This can be done via javascript, here is how I did it. The problem is I don't want to have this column definition syntax for every table in my app. Not two tables are identical, and to support all tables/columns like this it would result in bunch of javascript code for every table. I don't see this as a good practice.
$('.data-table').each(function(){
initialize_ajax_data_tables($(this));
});
function initialize_ajax_data_tables(element)
{
var display_rows = element.attr('data-rows') ? parseInt(element.data('rows')) : 25;
var initial_sort = element.attr('data-sort') ? element.data('sort') : [0, 'asc'];
dataTables = element.DataTable({
"processing": true,
"serverSide": true,
"ajax": {
url: base_url+'ajaxprocess/products_data_table.json',
type: 'GET'
},
"columns": [
{ "data": "id" },
{ "data": "product_type_name" },
{ "data": "code" },
{ "data": "name" },
],
"columnDefs": [
{
"render": function ( data, type, row ) {
return '<span class=\"label label-info\">'+ data +'</span>';
},
"targets": 1
},
{
"render": function ( data, type, row ) {
return '<span class=\"label label-success\">'+ data +'</span>';
},
"targets": 2
},
],
"pageLength": display_rows,
"order": initial_sort,
});
dataTables = $.fn.dataTable.fnTables(true);
}
Is there a way to somehow define this column definition/rendering in HTML itself and then pull this in the javascript when initialising DataTables? Or any other way on how to approach this issue?
For sorting rules and pageLength on the DataTables I use data-attributes from the <table> element and that works perfect. This way I define attributes like:
<table id="DataTables_Table_0" class="data-table" data-rows="50" data-sort="[0,"desc"]">
This works fine, but can not use this for columnDefs arrays as render attribute expects function.
I am making some progress and am posting my findings bellow. Maybe some find this useful, but I would still be open to other solutions in case you have a better design.
Currently I have split my code into two three sections:
Main application JS file: common DataTables initialisation code for all the application tables
View: HTML table view generated by the backend and served to the browser. In this view I define table specific properties which are then referenced in in common DataTable init code
Backend AJAX script which serves table data
So to demonstrate this with actual code.
1. Main initialisation code
$('.data-table').each(function(){
initialize_data_tables($(this));
});
function initialize_data_tables(element)
{
if(!(element instanceof jQuery)) element = $(element);
var table_defs = element.attr('data-table-def') ? eval(element.data('table-def')) : [];
dataTables = element.DataTable({
"processing": true,
"serverSide": true,
"ajax": {
url: table_defs.url,
type: 'POST'
},
"columns": table_defs.columns,
"pageLength": table_defs.rows,
"order": table_defs.sort,
});
dataTables = $.fn.dataTable.fnTables(true);
}
2. The HTML view
Here I define specific JS object for table definition, column definition and so on. Every table in app has specific definition. This structure also allows me to have multiple data tables on the view at the same time and reference the right JS object with table properties definition.
<script type="text/javascript">
var tableDef = {
url: "<?= Uri::create('utilities/ajaxprocess/products_data_table.json') ?>",
columns: [
{ "data": "id" },
{ "data": "product_type_name", render: function ( data, type, row ) {
return '<span class=\"label label-info\">'+ data +'</span>';
}
},
{ "data": "code" },
{ "data": "name" },
],
rows: 50,
sort: [ 0, 'desc' ]
};
</script>
<table class="data-table" data-table-def="tableDef”>...</table>
3. The backend
No need to paste my code here. Just functions that query my database and prepare data to be served via AJAX to DataTables.
Following your idea I would say try to define the render methods somewhere and bind them through data attributes.
This solution would be rather easy to test, but I don't think you can work around the columnDefs problematic.

I want to use JsArray with the Webix component DataTable

I want to use JsArray with the Webix component DataTable. But I have one problem. When I use JsArray format I can’t update the data in the Webix datagrid. Unfortunately, I can see only the beginning of its data. Check the sample to understand the issue:
var array1 = [ [1,"Marie","Oslo"],[2,"John","Los Angeles"],[3,"Kate","London"] ];
var array2 = [ [4,"Martin","Manchester"],[5,"Joana","Lisbon"],[6,"Ronaldo","Barcelona"],[7,"Matthew","Portland"] ];
webix.ui({
view:"button",
label:"test new data",
click: function() {
new_data()
}
});
webix.ui({
view:"datatable",
id: "mytable",
columns:[
{id:"data0", header:"ID" },
{id:"data1", header:"Name" },
{id:"data2", header:"City" }
],
datatype: "jsarray",
data: array1
});
function new_data () {
var mytable = $$("mytable");
mytable.parse(array2);
}
After pressing the button “test new data”, 4 new empty lines appear in the table.
To solve this issue, you should specify data format in the parse command
mytable.parse(array2, "jsarray");
The component will expect the json data, by default.
I hope that it'll help you)

Swapping data in Angular UI-Grid, new columns not visible when changing dataset externally

I've got a query tool I've been working on, which has an angular form that is filled out, and then when it's submitted it uses AJAX which returns JSON, which is then rendered into ui-grid, that JSON response looks like
{
"success": true,
"message": "",
"columns": ["first_name", "last_name", "company", "employed"]
"results": [
{first_name: "John", last_name: "Smith", company: "Abc Inc", employed: true},
{first_name: "Johnny", last_name: "Rocket", company: "Abc Inc", employed: true}]
}
I'm working on both the PHP and angular so I have full control over this JSON response if need be. I'm running into an issue when my JSON response from a first AJAX call is rendered, and then I run another, seperate AJAX call on the same page and get a new data set: this new data set does not render any of the columns that were not in the original data set. This is hugely problematic as the table is essentially cleared when none of the columns are the same, and I often need to load completely different data into ui-grid in this single page app.
When the JSON is recieved I simply bind the jsonResult.results to the old $scope.myData variable that ui-grid is bound to.
I've made a plunker isolating this issue. A dataset with a "punk" column is loaded, and then clicking "swap data" will try to load a dataset with "employee" column instead of "punk". I've so far looked into directives that will refresh or reload when the $scope.myData variable changes using $watch, and looked at finding something like $scope.columnDefs to let ui-grid know. Relatively new to angular and javascript so directives are still a bit over my head.
I have updated your plunker slightly:
$scope.swapData = function() {
if ($scope.gridOpts.data === data1) {
$scope.gridOpts.columnDefs = [
{ name:'firstName' },
{ name:'lastName' },
{ name:'company' },
{ name:'employee' }
];
$scope.gridOpts.data = data2;
//punk column changes to employee
}
else {
$scope.gridOpts.columnDefs = [
{ name:'firstName' },
{ name:'lastName' },
{ name:'company' },
{ name:'punk' }
];
$scope.gridOpts.data = data1;
//employee column changes to punk
}
};
http://plnkr.co/edit/OFt86knctJxcbtf2MwYI?p=preview
Since you have the columns in your json, it should be fairly easy to do.
One additional piece that I figured out with the help of Kevin Sage's answer and the plunker example... If you are using the backward-compatible "field" attribute the swapping does not work properly when there are field name overlaps between the two sets of column definitions. The column headers and the column widths are not rendered properly in this case. Using the "name" attribute of the column definition corrects this.
$scope.swapData = function() {
if ($scope.gridOpts.data === data1) {
$scope.gridOpts.columnDefs = [
{ field:'firstName' },
{ field:'lastName' },
{ field:'company' },
{ field:'employee' }
];
$scope.gridOpts.data = data2;
//punk column changes to employee
}
else {
$scope.gridOpts.columnDefs = [
{ field:'firstName' },
{ field:'lastName' },
{ field:'company' },
{ field:'punk' }
];
$scope.gridOpts.data = data1;
//employee column changes to punk
}
};
Example here: Plunker
My solution:
$http.get('url').success(function(res) {
// clear data
gridOptions.data.length = 0;
// update data in next digest
$timeout(function() {
gridOptions.data = res;
});
});

Select2 load JSON resultset via AJAX and search locally

Until now I've been using Select2's normal AJAX method of searching and filtering data serverside, but now I have a usecase where I want to retrieve all the results via AJAX when the select is opened and then use those results (now stored locally) to search and filter.
I've trawled the web looking for examples of how to do this and all i've found is lots of people saying the Query method should be used rather than the AJAX helper. Unfortunately I haven't found any examples.
So far all I've managed is the basic:
$('#parent').select2({
placeholder: "Select Parent",
minimumInputLength: 0,
allowClear: true,
query: function (query) {
//console.log(query);
query.callback(data);
}
});
data = {
more: false,
results: [
{ id: "CA", text: "California" },
{ id: "AL", text: "Alabama" }
]
}
Data is being passed to the select but query filtering is not implemented.
I'm struggling to understand the select2 documentation and would appreciate any assistance or links to examples.
Try the following - pre-load json data into local variable and when ready bind this to select2 object
<script>
function format(item) { return item.text; }
var jresults;
$(document).ready(function() {
$.getJSON("http://yoururl.com/api/select_something.json").done(
function( data ) {
$.jresults = data;
$("#parent").select2(
{formatResult: format,
formatSelection: format,
data: $.jresults }
);
}
)
});
</script>

Categories

Resources