datatables: how to repopulate table after data changed? - datatable

My goal is to repopulate/redraw/refresh table after aaData:'data' changed:
$(tableid).dataTable({
"aaData": data,
"destroy": true,
"aoColumns": columns
});
I suceed with some tricky:
$(tableid).dataTable().fnClearTable();
$(tableid).dataTable().fnDestroy();
$(tableid).dataTable({
"aaData": data,
"destroy": true,
"aoColumns": columns
});
which looks very horrible. I guess there must be a cleaner way to do that ?

I've had this struggle with datatables also.
My solution:
var data = [json loaded with ajax]
function loadTable(data){
if($.fn.DataTable.isDataTable('#testsListTable')){
if(data.testRunReports.length == 0)
$('#testsListTable').dataTable().fnClearTable();
else
$('#testsListTable').dataTable().fnAddData(data);
return;
}
$('#testsListTable').DataTable({
data: data,
...

Related

Dynamic value of columns Datatable

i create datatable, i want create dynamically columns data.
my init datatable looks like this :
var columnsData = [
{data: 'name'},
{data: 'phone'}
];
var dtable = $('#dtable').DataTable({
serverSide : true,
ajax : '/data',
columns : columnsData,
});
in some condition, make columns data changed. i don't have solution for that.
example columns what i want to change :
columnsData = [
{data: 'name'},
{data: 'address'}
]
i was try
dtable.columns.data( columnsData ).load();
dtable.columns.data( columnsData ).draw();
but still doesn't work.
You can use the below function to recreate the data table with changes in structure.
function getDT() {
$.ajax({
url: '/data',
success: function (data) {
data = JSON.parse(data);
columnNames = Object.keys(data.data[0]);
for (var i in columnNames) {
columns.push({data: columnNames[i],
title: capitalizeFirstLetter(columnNames[i])});
}
$('#dtable').DataTable( {
processing: true,
serverSide: true,
ajax: '/data',
columns: columns
} );
}
});
}
please find the complete implementation on Example

JQGrid dynamically created column headers

I am creating column headers from the rows of a mysql table (Button1) and it works fine. eg: I get headers |A|B|C| in the grid when I query the table for the rows A, B, C.
Button2 queries the same table to get different rows eg D, E. Both queries return expected data.
But, the new header data from Button2 is appended to the column headers created from Button1. ie I get |A|B|C|D|E|.
What I want is just the headers |D|E|. How can I clear the old column headers and replace with the new?
Thanks for any help.
var ColModel = []
var availabilitydept = ''
$("#button1").click(function() {
availabilitydept = 'de85768424332'
set_up_avgrid()
});
$("#button2").click(function() {
availabilitydept = 'de56827997021'
set_up_avgrid()
});
function set_up_avgrid()
{
$("#avgrid").jqGrid("GridUnload")
$('#avgrid').jqGrid('clearGridData');
create_colmodel()
create_grid()
}
function create_colmodel()
{
ColModel.push({name :'Date',index: 'dateindex',resizable : false, align:'left',
frozen : true, width : 80, search: false,
resizable : false});
$.ajax
({
url: 'tl2_get_rooms_by_dept.php',
type: 'GET',
async: false, // ** it don't work with async true.
data: 'userid=' + 'TL2-0001'
+ '&deptid=' + availabilitydept,
dataType: 'json',
success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
ColModel.push({name: row.roomname, index: row.roomname + i, align:'center', resizable : false, width:50, search:false});
}
}
});
}
function create_grid()
{
$("#avgrid").jqGrid(
{
shrinkToFit: false,
height : 200,
width : 290,
colModel: ColModel,
});
}
Solved: I'm sure there are better ways but what I ended up doing was to change my query to select all rows from the mysql table, then create the grid. Of course the grid then had a column for each row in the table. To get rid of the unwanted columns I composed a function to loop through the column names and hide/show as required using.
$"#avgrid").jqGrid('hideCol',[row.roomname]);
$("#avgrid").jqGrid('showCol',[row.roomname]);

Datatables Ajax call not displaying data

I'm using the datatables library to display some data and would like to update this every 30 seconds with data fetched form a URL. I've followed the api documentation and have implemented the code below to do this:
$( document ).ready(function() {
var table = $('#performance_summary').DataTable( {
ajax: 'https://myjasonurl.com'
} );
setInterval( function () {
table.ajax.reload();
}, 30000 );
});
When the page loads I can see that the correct URL is called to retrieve data, and data is returned in the correct format to display properly in the table (I've checked this works by loading this into the table directly). Unfortunately the resulting datatable when using the ajax call states that it is "loading" but never loads/shows the data, does anyone have any idea of how I fix this?
Try the DataTable().ajax.url function,
Following code works fine for me:
$(document).ready(function() {
var table = $('#performance_summary').DataTable({
paging: false,
searching: false,
ajax: "https://api.myjson.com/bins/897v1",
columns: [{
"title":"Test",
"data": "test"
}]
});
setInterval( function () {
$('#performance_summary').DataTable().ajax.url(
"https://api.myjson.com/bins/897v1"
).load();
}, 3000 );
});
here's the fiddle: https://jsfiddle.net/ju2bmtm7/84/

jqGrid: How to load only rows that an attribute is set to true

I have a JSON Object as the following:
{
"rows": [
{
"id":1,
"name": "Peter",
"hasData": true,
},
{
"id":2,
"name": "Tom",
"hasData": false,
}]
}
And I want the jqGrid to load only rows that have data, meaning when "hasData" == true.
I am firstly wondering what is the best way to do such and secondly wondering how to do it.
UPDATE:
I have tried the following:
gridComplete: function(){
var rowObjects = this.p.data;
for(var i = 0; i<rowObjects.length;i++){
if(rowObjects[i].hasData == false){
$(this).jqGrid('delRowData',rowObjects[i].id);
}
}
},
but the problem is when I go to the next page, all the data is loaded new from the JSON.
I suppose that you load the data from the server using datatype: "json" in combination with loadonce: true option. The solution is very easy if you use free jqGrid fork of jqGrid. Free jqGrid allows to sort and to filter the data, returned from the server, before displaying the first page of data. One need to add forceClientSorting: true to force the applying the actions by jqGrid and postData.filters with the filter, which you need, and the option search: true to apply the filter:
$("#grid").jqGrid({
...
datatype: "json",
postData: {
// the filters property is the filter, which need be applied
// to the data loaded from the server
filters: JSON.stringify({
groupOp: "AND",
groups: [],
rules: [{field: "hasData", op: "eq", data: "true"}]
})
},
loadonce: true,
forceClientSorting: true,
search: true,
// to be able to use "hasData" property in the filter one has to
// include "hasData" column in colModel or in additionalProperties
additionalProperties: ["hasData"],
...
});
See the demo https://jsfiddle.net/OlegKi/epcz4ptq/, which demonstrate it. The demo uses Echo service of JSFiddle to simulate server response.
I can recommend you another solution (in case you use Guriddo jqGrid) , which can be used with any datatype and any settings. The idea is to use beforeProcessing event to filter the needed data.
For this purpose we assume that the data is like described from you. Here is the code:
$("#grid").jqGrid({
...
beforeProcessing : function (data, st, xhr) {
var test= data.rows.filter(function (row) {
if(row.hasData == true ) { // true is not needed but for demo
return true;
} else {
return false;
}
});
data.rows = test;
return true;
}
...
});
I suppose the script will work in free jqGrid in case you use them

How to pre-load an array via ajax and use it for select2?

My general problem is that I want to have a Javascript variable which I then use with select2, to prepare the options for a select multiple. I have a fairly large array (7000 objects) and just want to store that once in a variable rather than constantly polling the server with search terms. Here is what I got.
The HTML is simply:
<input type="hidden" id="group_a" multiple="multiple" placeholder="Select at least two treatments">
Now, when I write the variable directly everything works as expected:
var treatments = [{id: 1, text: "you"}, {id: 2, text: "me"}];
$("#group_a").select2({
data: treatments,
minimumInputLength: 1,
multiple: true,
closeOnSelect: false,
width: "660px"
});
However, when I use ajax to load the array things get weird. My code to do that:
$.ajax({
url: '/funny/url',
}).done(function(data) {
treatments = data.choices;
});
I tend to get the following error unless I use the debugger to step through the code, then it works as expected. So could this somehow be a timing issue?
uncaught exception: query function not defined for Select2 group_a
My complete javascript looks like below and I've also prepared a fiddle which shows the same error.
$(document).ready(function() {
var treatments;
$.ajax({
url: '/funny/url',
}).done(function(data) {
treatments = data.choices;
});
$("#group_a").select2({
data: treatments,
minimumInputLength: 1,
multiple: true,
closeOnSelect: false,
width: "960px"
});
});
The ajax call is asynchronous, so at the time you are instrumenting the Select2 control, treatments is still undefined.
You could do the following:
$(document).ready(function() {
$.ajax({
url: '/funny/url',
}).done(function(data) {
$("#group_a").select2({
data: data.choices,
minimumInputLength: 1,
multiple: true,
closeOnSelect: false,
width: "960px"
});
});
});
jsfiddle
Better yet though, I would do the following.
Initially set treatments to an empty array, and use a function for the data option so if treatments is changed, the changes will be picked up by the Select2 control. That way, you can instrument the Select2 control right away, and then update treatments with the data returned by the ajax call. Additionally, you could initially disable the Select2 control, and then enable it when the ajax call returns.
$(document).ready(function() {
var treatments = [];
$.ajax({
url: '/funny/url',
}).done(function(data) {
treatments = data.choices;
$("#group_a").select2('enable', true);
});
$("#group_a").select2({
data: function() { return { results: treatments }; },
minimumInputLength: 1,
multiple: true,
closeOnSelect: false,
width: "960px"
}).select2('enable', false);
});
jsfiddle
The third option would be to keep your original code, but make the ajax call synchronous. I recommend not doing that though. When you make an ajax call synchronous, you lock up the entire browser.
Here is my solution. Thanks to #John S for the initial approach, but I couldn't get the select2 formatter to parse my array. Select2 box would tell me 'no results found.' I ended up running a for loop through my array and writing out the :id, :text hashes.
Starting with my json ajax call is an array of string 'terms':
// localhost:3000/search/typeahead_terms_all.json
[
"Super Term",
"cool term",
"killer term",
"awesome term",
"try term",
"param term",
"try name",
"Academic Year",
"grade average",
"Hello Term",
"Academic Calendar",
"kinda cool term",
"My Term",
]
Then the javascript:
$(document).ready(function() {
var term_names_array = [];
$.ajax({
url: '/search/typeahead_terms_all',
}).done(function(data) {
// Here I iterate through my array of strings and write out the hash select2 needs
for (index = 0; index < data.length; ++index) {
term_names_array.push({ id: index, text: data[index] });
}
$('.report_term_input').select2('enable', true);
});
$('.report_term_input').select2({
dataType: 'json',
data: term_names_array,
multiple: true,
width: "500px"
});
});

Resources