How to refresh datatable list jquery? - javascript

I am using DataTable Jquery for bind list of records. I face below issue.
I am using jquery model popup for addnew and update record in MVC 4.0 Razor with no submit button only using ajax function. When I am click on "save" button and I want to update list with latest changes, but it can not. My code as below.
For Index page for list bind.
<script type="text/javascript">
$(document).ready(function () {
if (fnServerObjectToArray) {
var oTable = $('.datatable').dataTable({
"bJQueryUI": true,
"sScrollX": "",
"bSortClasses": false,
"aaSorting": [[0, 'asc']],
"bAutoWidth": true,
"bInfo": true,
"sScrollY": "100%",
"sScrollX": "100%",
"bScrollCollapse": true,
"sPaginationType": "full_numbers",
"bRetrieve": true,
"bProcessing": true,
"sAjaxSource": $('.datatable').attr('data'),
"aoColumns": [
{ sType: 'string' },
{ sType: 'string' },
{ sType: 'string' },
{ sType: 'string' },
{ bSortable: false }
],
"fnServerData": fnServerObjectToArray()
});
}
});
fnServerObjectToArray = function () {
return function (sSource, aoData, fnCallback) {
$.ajax({
"dataType": 'json',
"type": "GET",
"url": sSource,
"data": aoData,
"success": function (json) {
var a = [];
for (var i = 0, iLen = json.aaData.length; i < iLen; i++) {
var inner = [];
inner.push(json.aaData[i].Name);
inner.push(json.aaData[i].Price);
inner.push(json.aaData[i].Phone);
inner.push(json.aaData[i].Email);
inner.push("<a title='Edit Place' class='EditDialogPlacesToStay' href='/placetostay/" + json.aaData[i].Id + "/edit'><img src='/Content/images/icons/small/grey/pencil.png' title='Edit' /></a> <a class='DeleteConfirm' href='/placetostay/" + json.aaData[i].ID + "/delete'><img src='/Content/images/icons/small/grey/trashcan.png' title='Delete' /></a>");
a.push(inner);
}
json.aaData = a;
fnCallback(json);
},
"error": function (error) {
}
});
}
}
</script>
On save button in success function I call the location.reload().
But I could not bind the latest changes of records means List is not refreshed.
Please help me for same.

Wrap the datatable initialization into a function, like initDataTable(), and add the option bDestroy to the settings :
function initDataTable() {
if (fnServerObjectToArray) {
var oTable = $('.datatable').dataTable({
"bDestroy" : true, //<-- add this option
"bJQueryUI" : true,
...
//anything as above
});
}
}
$(document).ready(function () {
initDataTable();
});
when you want to refresh / reload, like by a click on a button :
<button id="refresh">Refresh</button>
$("#refresh").click(function() {
initDataTable();
});
here is a demo -> http://jsfiddle.net/cxe5L/
To avoid the cache-issue
jQuery dataTables has hardcoded cache : true into its AJAX-calls. You have "sAjaxSource": $('.datatable').attr('data'). I assume data holds the path to an external resource, like /data/getdata.asp or similar? Add a timestamp as param to that resource, like
sAjaxSource : $('.datatable').attr('data')+'?param='+new Date().getTime()
so the sAjaxSource becomes on the form
/data/getdata.asp?param=1401278688565
This is basically the same thing jQuery is doing, when cache : false is set on a AJAX-request.

location.reload() will refresh the page content and your
$(document).ready(function () {}
is executing again instead of getting the latest changes. Check weather your database has new records or not.

Related

Ajax request don't start immediately

How can i stop this from autoplaying, I have a search button and I want to search first before getting the data, any approach is okay to me, whether it's AJAX side or Javascript side, please help.
Javascript
var table = $('#SARDatatable').DataTable({
"processing": true,
dom: "<'row'<'col-sm-6'l><'col-sm-6'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-2'i><'col-sm-5'B><'col-sm-5'p>>",
buttons: [
'copyHtml5',
'excelHtml5',
'csvHtml5',
'pdfHtml5',
'print'
],
"ajax": {
"url": '/Home/GetAllSAR',
"type": "POST",
"datatype": "json",
"data": function (d) {
d.searchParameters = {};
d.searchParameters.sarcode = $('#txtSAR').val();
d.searchParameters.stype = $('#txtSType').val();
}
},
"columns": [
{ "data": "sarcode", "autoWidth": true },
{ "data": "stype", "autoWidth": true },
{ "data": "amount", "autoWidth": true },
{ "data": "filterno", "autoWidth": true }
]
});
$('#btnSearch').on("click", function () {
table.ajax.reload();
});
If I understand you correctly, you would like to only initialize the table after a button has been clicked, so that the AJAX request to get the data will not be issued before clicking the button.
If this is the case, then I would suggest the following:
Have a button that inits the table:
HTML
<button id='initTable'>Init Table</button>
JavaScript
var table;
$('#initTable').on('click', function() {
table = $('#SARDatatable').DataTable({ // code to init the DataTable });
});
Have the 'reload' button
HTML
<button id='btnSearch'>Reload</button>
JavaScript
$('#btnSearch').on("click", function () {
table.ajax.reload();
});
After you init the table, you can hide the "Init Table" button, so that there will be only one button at a time.
Hope this helps.

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 change jquery datatable value by dropdown value change

I am using jquery datatable to display table data based on dropdown list value, I am using ajax to get data from the table.
The problem is when the table first loads it is working fine but when I click on sort or search it displays processing which does not change until i refresh the page,the code is given below:
$( document ).ready(function() {
var table = $('#example').DataTable({
//"bProcessing": true,
//"sAjaxSource": "response.php",
"processing": true,
"serverSide": true,
//"bDestroy": true,
// "bJQueryUI": true,
"aoColumns": [
{ mData: 'FNAME' } ,
{ mData: 'FPRICE' },
{ mData: 'IMGPATH' },
{ mData: 'FDESC' },
{ mData: 'CID' }
],
"ajax": {
'type': 'POST',
'url': 'response.php',
'data': {id: $('#myselect').val()}
// "success":function (res) {
//
// }
}
});
$('#myselect').change(function() {
var item = $(this).val();
// alert(item)
var urld = 'response.php/'+item;
table.ajax.url(urld).load();
table.reload();
});
// setInterval( function () {
// table.ajax.reload();
// }, 10000 );
//table.fnDraw();
});
If you are using serverside processing check this out for custom sort https://datatables.net/forums/discussion/9857/server-side-processing-custom-sort-solution-like-formatted-num-sorting-plug-in

jquery data table and sorting columns

I'm using jquery data table to display large amounts of data inside grid. I implemented server side pagination but I'm struggling with sorting data server side.
Below is my datatable initialization, answer with query for sorting is not the subject here, I just need a way to pass information of which column is clicked to the controller, the one upon I will do the sorting.
('#myTable').dataTable({
"processing": true,
"serverSide": true,
"info": false,
"pageLength": 10,
"lengthChange": false,
"stateSave": false,
"bPaginate": true,
"bFilter": false,
"sPaginationType": "full_numbers",
"info": "Page _PAGE_ from _PAGES_",
"infoEmpty": "No data",
"oPaginate": {
"sFirst": "First",
"sPrevious": "Previous",
"sNext": "Next",
"sLast": "Last"
},
"ajax": {
"url": "#string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"))/MyController/GetData",
"type": "GET",
"data": function (d) {
.....
},
},
preDrawCallback: function (settings) {
...
},
drawCallback: function (settings) {
...
},
"columns": [
{ "data": "Id" },
{ "data": "FirstName" },
{ "data": "LastName" },
{ "data": "Age" }
],
"columnDefs": [
{
targets: [0],
orderable: false
},
{
render: function (data, type, row) {
...
}
],
"order": [[0, "desc"]]
});
public ActionResult GetData(){
var sortColumn = ...
...
}
You can bind the 'order' event like this:
$('#myTable').on( 'order.dt', function () {
var order = table.order();
var column_selected = order[0][0];
var order_way= order[0][1];
doStuff(column_selected ,order_way);
});
See it in plugin reference
By specifying "serverSide": true,, datatables will by default add information to the request which you need to use in your server-side code. If you look in the Firebug Network panel, you will be able to see the request with the querystring parameters. See here for the full list of parameters. Note that the link is to the v1.9 documentation, because that's what it looks like you're using.
So for sorting, you'd be interested in iSortCol_0 and sSortDir_0 which relate to the clicked column and the sort direction respectively.
In your controller method, you would access the parameters like this:
var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
var sortColumnDir = Request["sSortDir_0"];
You then need to incorporate this, and the other parameters into your query.
Here is an article on using server-side datatables with MVC

jQuery Datatables.net - refresh table - getting null sAjaxSource

I have the following function which should update a datatable in my ASP.NET site master page:
function refreshTable(oTable) {
var table = $(oTable).dataTable();
var oSettings = table.fnSettings();
//Retrieve the new data with $.getJSON. You could use it ajax too
$.getJSON(oSettings.sAjaxSource, null, function (json) {
table.fnClearTable(this);
for (var i = 0; i < json.aaData.length; i++) {
table.oApi._fnAddData(oSettings, json.aaData[i]);
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
table.fnDraw();
});
}
This function is then called to refresh a table if an attachment is added to the site - this is the datatable settings that it should refresh.
var DeleteClicked = false;
var oTable;
$(document).ready(function () {
oTable = $('#infoTable').dataTable({
"aaSorting": [[6, "desc"]],
"bProcessing": true,
"sAjaxSource": '/Web/Handlers/infoTableHandler.ashx',
"aoColumns": [
{ "mData": "ID", "bVisible": false },
{ "mData": "Type" },
{ "mData": "Received" },
{
"mData": "Action", "sWidth": "100px", "mRender": function (data, type, row) {
var id = row.ID;
return "<input type=button id=" + id + " onclick='DeleteFile(" + id + ")' class=buttonBlue value=Delete />";
},
},
{ "mData": "IsImage", "bVisible": false }
],
"bDeferRender": true,
});
However - if I open Developer Tools in Chrome I get an error message saying sAjaxSource is null so i cannot then get the value from it - so oSettings is null and then I cannot get access to the sAjaxSource - anyone see anything wrong here?
you're basically reinitializing your dataTable in the first row of refreshTable. Try instead:
function refreshTable() {
var oSettings = oTable.fnSettings();
...
}
and refer directly to the global oTable instead of your local table variable

Categories

Resources