Custom REST datasource with jQuery DataTables - javascript

I have a REST endpoint with a page and size parameter:
http://someservice.com/api/accounts/10/0
In this example it returns the first page and every page has 10 records.
Now, I want to use DataTables, and found this example on StackOverflow, where I can add the data to the table from the REST response to the table.
But, this way, I add all the data to the table. I want to be able to add the data page per page, and make requests to the endpoints page per page. For example, on page load, I make a REST request for that page. When I click to the second page, I make a request again, for the data for that one.
Any way to do this in DataTables?

This should work:
function fnGetKey( aoData, sKey ){
for ( var i=0, iLen=aoData.length ; i<iLen ; i++ ){
if ( aoData[i].name == sKey )
return aoData[i].value;
}
return null;
}
$('#example').dataTable( {
"bServerSide" : true,
"sAjaxSource" : "http://someservice.com/api/accounts/10/0", //first page
"sPaginationType": "two_button",
"fnServerData": function ( sSource, aoData, fnCallback ) {
var startIndex = fnGetKey(aoData, "iDisplayStart")
var length = fnGetKey(aoData, "iDisplayLength")
sSource="http://someservice.com/api/accounts/"+length+"/"+(startIndex/length + 1)
$.getJSON( sSource, aoData, function (json) {
fnCallback(json)
} );
}
});
So when you click on next page or previous, you need to calculate at what page you are now and by changing source you do a trick.

Related

UI Grid refresh in Angular

From a different controller a modal pop up opens. On closing of the modal pop up , I will do something and I want to transfer the data to a different controller which populates a UI grid and is bound to $scope.searchResultsGridOptions.
So in my ABCCtrl.js file :
On closing of a modal , I do :
$("#iConfirmationModal").on('hidden.bs.modal', function () {
$state.go('transaction.search.results', {});
//I close all the modals
$uibModalStack.dismissAll();
//I get the stored search criteria
var searchResultsParam = TransactionDataServices.getSavedSearchParams();
//Using them I hit the web service again and get the data to reload the UI Grid
TransactionServices.getTransactionAdvSearchResults(searchResultsParam).then(function (result) {
//I got the result
console.log(result);
/Now I want to reload the grid with this data , but the grid scope object which binds to this , is in separate controller
searchResultsGridOptions.data = result;
});
});
In DEFCtrl.js
I have
getSearchResultsGridLayout: function (gridOptions, uiGridConstants, datas) {
gridOptions.multiSelect = false;
// gridOptions.data.length = 0;
// gridOptions.data = '';
gridOptions.data = datas;
console.log("Grid Data ");
console.log(datas);
console.log(gridOptions.data);
angular.element(document.getElementsByClassName('grid')[0]).css('height', '0px');
// console.log(datas.length);
return gridOptions;
}
But how would I only change the data only when modal closes ?
Rest of the time it should not refresh the Grid ?
Or ,
Is there any way when on closing of the modal , instead of simply go back to the state using $state.for() and seeing the previous unrefreshed data , I can see the refreshed data ?
Hi I think you do not need to call the "TransactionServices.getTransactionAdvSearchResults()" in the "ABCCtrl" controller but you have to call it in the "DEFCtrl" controller.
You need to find a way to pass the "searchResultsParam" extracted in "ABCCtrl" to "DEFCtrl".
You can use the ui-router state parameters. You can specify a parameter in the "transaction.search.results" state, like this:
.state('transaction.search.results', {
...
params: {
searchResultsParam: null
}
...
})
And in the "ABCCtrl" pass it to the state:
$("#iConfirmationModal").on('hidden.bs.modal', function () {
//I close all the modals
$uibModalStack.dismissAll();
//I get the stored search criteria
var searchResultsParam = TransactionDataServices.getSavedSearchParams();
$state.go('transaction.search.results', {searchResultsParam: searchResultsParam});
Then, in "DEFCtrl" you can read it and call the "TransactionServices.getTransactionAdvSearchResults()" method.

How to stay on the active page in jquery DataTable

I have several data listed on the jquery dataTable and its done pagination by the DataTable plugins default. I want to get the current page of the dataTable while processing the data and set that page into active after the action is processed and reload the data.
See this fiddle. You can see how to get the current pages. In the JSFiddle you can try refresh browser. Example let say the current page now is 3. When you refresh the browser, you still in page 3.
To solve your problem want to go back to the last page when editing or deleting row, u must use this option to make jquery datatable remember where the last page. Jquery Datatable will save the state of a table (its paging position, ordering state etc). The state saving method uses the HTML5 localStorage and sessionStorage APIs for efficient storage of the data. See this link to read more detail about it. State saving
"bStateSave": true
JSFiddle Link
Fiddle Demo
Javascript code
$(document).ready(function() {
var table = $('#example').DataTable({
"sPaginationType": "full_numbers",
"bStateSave": true
});
$("#example").on('page.dt', function () {
var info = table.page.info();
$('#pageInfo').html('Currently showing page ' + (info.page + 1) + ' of ' + info.pages + ' pages.');
});
} );
Use only stateSave: true
like this:
$(document).ready(function() {
$('#tableId').DataTable( {
stateSave: true
} );
})
Copied from Datatable
var table = $('#example').DataTable( {
ajax: "data.json"
} );
setInterval( function () {
table.ajax.reload( null, false ); // user paging is not reset on reload
}, 30000 );
Pass null, false on reload function to stay on that page while reloading the table. See ajax.reload() documentation for more information.
See the dataTables documentation which provides a call back function from which you can obtain the current page:
$('#example').dataTable( {
"drawCallback": function( settings ) {
var api = new $.fn.dataTable( settings );
// Output the data for the visible rows to the browser's console
// You might do something more useful with it!
console.log( api.rows( {page:'current'} ).data() );
}
});
Add this where you are initializing datatable
"drawCallback": function( settings ) {
alert ( 'You are on ssame page' );
}
It works for me :)

TypeError: oTable.fnReloadAjax is not a function - DataTables

i thought i will have no more problems with dataTables as its working now even the refresh.
Turns out some time it works in some places, but in some places it just give this stupid error.
TypeError: oTable.fnReloadAjax is not a function
Well i have a functon which adds new data in table, after success i want datatable to refresh.
it did work on other view but now As i have created this view, it is not working.
Im using Ignited Datatables.
i have a common.js file includes the datatables script. this script is working fine.
function commonDataTables(selector,url,aoColumns){
var responsiveHelper;
var breakpointDefinition = {
tablet: 1024,
phone : 480
};
oTable = selector.dataTable({
sPaginationType: 'bootstrap',
oLanguage : {
sLengthMenu: '_MENU_ records per page'
},
"autoWidth" : false,
"aoColumns":aoColumns,
"bServerSide":true,
"bProcessing":true,
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"sAjaxSource": url,
"iDisplayLength": 25,
"aLengthMenu": [[2, 25, 50, -1], [2, 25, 50, "All"]],
'fnServerData' : function(sSource, aoData, fnCallback){
$.ajax ({
'dataType': 'json',
'type' : 'POST',
'url' : sSource,
'data' : aoData,
'success' : fnCallback
}); //end of ajax
},
'fnRowCallback': function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
$(nRow).attr("data-id",aData[0]);
responsiveHelper.createExpandIcon(nRow);
return nRow;
},
fnPreDrawCallback: function () {
// Initialize the responsive datatables helper once.
if (!responsiveHelper) {
responsiveHelper = new ResponsiveDatatablesHelper(selector, breakpointDefinition);
}
},
fnDrawCallback : function (oSettings) {
// Respond to windows resize.
responsiveHelper.respond();
}
});
}
Then in my Codeigniter View file.
oTable = '';
//Data Tables Script Here.
var selector = $('#ManageTabs');
var url = "{{base_url()}}admin/configurations/listTabs_DT/";
var aoColumns = [
/* ID */ {
"bVisible": false,
"bSortable": false,
"bSearchable": false
},
/* Tab Name */ null,
/* Tab Order */ null,
/* Tab Desc */ null,
/* Actions */ null
];
commonDataTables(selector,url,aoColumns);
//End Of dataTables Script..
i am using oTable as global variable so defined the oTable outside the document.ready function
var oTable;
i know its a bad practice to use global variable but i wanted to find a work around to make the datatable refresh all the data.
Well this global variable Method did worked out for 1 view but in this next view i get the error which i told you already.
Here, below is the code of the button where in success it should have performed its duty but instead it gave error..
$('#createTabBtn').on('click', function(e){
//e.stopImmediatePropagation();
e.preventDefault();
var selector = $('#createTabModelForm');
HRS.formValidation(selector);
if(selector.valid()){
var formData = {
TabName : $("#cTabName").val(),
TabOrder : $("#cTabOrder").val(),
TabDesc : $("#cTabDesc").val()
};
$.ajax({
type:"post",
url:"{{base_url()}}admin/configurations/addNewTab/",
dataType:"json",
data: formData,
success: function(output){
if (output == true){
oTable.fnReloadAjax();
}
}
});
//Do Stuff After pressing the Create Button.
// Close the Modal
$('#addNewTabModal_ManageTabs').modal('hide');
// Reset All the TextBoxes and CheckBoxes
$("#createTabModelForm")[0].reset();
// Reset/Empty All the Select2 Dropdowns
//jQuery('.select2-offscreen').select2('val', '');
}
else{
//The Else Portion if you want Something else to Happen if not validated Form
}
});
Please can anyone know the best way to refresh the dataTables..
OMG, i forgot to add the fnReloadAjax.js file. i added that in first view but forgot to add in this view..
so anyone if face any problem like this, just see if the js file is attached.
being careless cost me my time but eventually problem solved.
But still there is a issue of Global Variable i mean i use global variable to refresh the grid.
if anyone has better option to use this fnreloadajax function. plz share.

cant select value of jqGrid autocomplete

I use a jqGrid with jquery autocomplete on one column.
{
name : 'mdmKndcode',
index : 'mdmKndcode',
width : 150,
align : "center",
editable : true,
edittype: 'text',
editoptions: {
dataInit: function(elem) {
var cache = {};
$(elem).autocomplete({
source: function( request, response ) {
var term = request.term;
console.log(term);
if(term in cache){
response(cache[term]);
return
}
$.getJSON( "/example/json/"+term, request, function( data, status, xhr ) {
cache[ term ] = data;
response( data );
});
},
minLength:3
});
}
}
In the grid I can see the results of json request in autocomplete list. This works fine. But I am not able to select a value in this list. The autocomplete list getting closed and lose the focus of the column after a mouseover or Keyboard press on the list.
Tried also with "select" function but same result.
Want to have the selection of the values in the list like in this Demo
Looking at your jsfiddle, the problem is that you are including jqueryui twice jquery-ui.js and jquery-ui-custom.min.js , most likely both of them have autocomplete and that causes troubles.
Remove one of them and that will fix the issue.
See here

JQuery DataTable Cell from a row click

I am trying to implement a function on jquery datatable, that returns the 1st and the 4th column of a clicked row
i am following this example, which allows me to manipulate a clicked row
http://datatables.net/examples/api/select_single_row.html
thinking that i can change this handler to do the read cell value procedures and use the value on my own logic
/* Add a click handler to the rows - this could be used as a callback */
$("#example tbody").click(function(event) {
$(oTable.fnSettings().aoData).each(function (){
$(this.nTr).removeClass('row_selected');
});
$(event.target.parentNode).addClass('row_selected');
});
i have also come over with this little code segment from dataTable forum http://datatables.net/forums/comments.php?DiscussionID=1384&page=1#Item_0
$('#example tbody tr').click( function () {
// Alert the contents of an element in a SPAN in the first TD
alert( $('td:eq(0) span', this).html() );
} );
may i have any pointer so i can get the 1st and 4th column of the clicked field?
next part
I have the above solved, thanks nick
however i have the next part of the problem. when i init the table
i use
/* Init the table */
oTable = $('#filetable').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "/crvWeb/jsonFileList.do",
"fnServerData": function ( sSource, aoData, fnCallback ) {
$.ajax( {
"dataType": 'json',
"type": "POST",
"url": sSource,
"data": aoData,
"success": fnCallback
} );
}
} );
my servlet takes a dir request parameter and returns a listing to the datatable as json response.
/crvWeb/jsonFileList.do
how can i add and get serlvet response with post request so i can have my table updated?
You can use .delegate() easiest here, like this:
$("#example tbody").delegate("tr", "click", function() {
var firstCellText = $("td:first", this).text();
var fourthCellText = $("td:eq(3)", this).text();
});
You can try out a demo here
With .delegate() this refers to the <tr> since that's the click we're handling, making things quite a bit cleaner..and it's still only one event handler at the <tbody> level, not one per <tr>.
This should do the trick, if I'm reading your code correctly:
$("tr.row_selected td:nth-child(1), tr.row_selected td:nth-child(4)");
It should return the first and fourth child of all tr elements with the class row_selected.

Categories