TLDR;
How to stay on the page in datatable using ajax my way?
My problems
User click a button in the table. That particular row will be updated and I will call the fn_GetData() function.
I will fetch the updated data from database into the table again, thus updating the row (actually entire table was updated).
If the row is few page later, when the table reload, it will back to the first page again. How to remain on that particular page?
Btw I tried .ajax.reload( null, false ) is not working
Ajax wrapped in javascript function
function fn_GetData(){
$.ajax({
url: "action/myfile.php",
type: "POST",
data: {'GetData':''},
dataType: "json",
success: function(data) {
if(data.status=='success'){
if ($.fn.DataTable.isDataTable("#myTable")) {
$('#myTable').DataTable().clear().destroy();
}
var myTable = $('#myTable').html(data.table).DataTable({
responsive: {
details: {
type: 'column'
}
},
"dom": 'Bplirtip',
}).columns.adjust().responsive.recalc();
//myTable.ajax.reload( null, false );
}
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr);
}
});
}
Enable state saving:
$('#example').dataTable( {
stateSave: true
} );
Related
I'm trying to add <tr/> tags dynamically to a DataTable, but I didn't find actual good documentation on how the "adding TR process" is supposed to work. I have this as my DataTables setup:
$("#Grid").DataTable({
stateSave: true,
fixedHeader: true,
rowReorder: true,
.
.
columnDefs: [
{ orderable: false, className: "seq-cell", targets: 0 },
{ orderable: false, targets: "_all" }
]
})
.on("row-reordered", function (e, diff, edit) {
for (var i = 0; i < diff.length; i++)
{
..
}
});
I'm getting the definition of the item in the grid from an MVC action method as an HTML string, via a jQuery AJAX statement:
$.ajax({
type: "post",
url: "AddItem",
data: $("#newitemform").find(":input[name]").serialize(),
success: function (d) {
var $body = $("#Grid tbody");
$body.append(d);
}
});
The "d" parameter is the HTML for a row; I'm appending it to the body. That adds correctly and but doesn't have the row reorder functionality enabled then. What is the proper way to append to a DataTable, then re-enable whatever functionality?
Use row.add() API method to add a new row instead of appending to the table body.
If d contains string in the following format <tr>...</tr>, you could just use $("#Grid").DataTable().row.add($(d).get(0)) to add a new row.
For example:
$.ajax({
type: "post",
url: "AddItem",
data: $("#newitemform").find(":input[name]").serialize(),
success: function (d) {
$("#Grid").DataTable().row.add($(d).get(0)).draw();
}
});
See this example for code and demonstration.
The best option is to use Datatables API's to add rows to the table. As indicated in the previous response you can use either row.add() or rows.add(). The data needs to be in a data structure that matches your Datatables data structure config, ie, arrays or objects.
However it looks like you are receiving HTML structured data and appending directly to the table. In this case Datatables is not aware of the added data. You will need destroy (destroy()) the Datatables table, append your data then re-init Datatables. For example:
$.ajax({
type: "post",
url: "AddItem",
data: $("#newitemform").find(":input[name]").serialize(),
success: function (d) {
$("#Grid").DataTable().destroy();
var $body = $("#Grid tbody");
$body.append(d);
$("#Grid").DataTable({
stateSave: true,
fixedHeader: true,
rowReorder: true,
.
.
columnDefs: [
{ orderable: false, className: "seq-cell", targets: 0 },
{ orderable: false, targets: "_all" }
]
})
}
});
I have the following problem: I am following these tutorials to be able to save the data in array through each row selected by a checkbox.
https://www.gyrocode.com/articles/jquery-datatables-checkboxes/
https://jsfiddle.net/gyrocode/abhbs4x8/
As in the provided link, I receive data in JSON to load my dataTable, now I am seen in need of, by a button to bring new data to my dataTable for it and added some more functions to the code that is in the link that Provide, and are as follows:
To delete the datatable:
function destroy_data_table(){
var table = $('#example').DataTable({
if (table != undefined){
table .fnDestroy();
}
}
In the click of the button I destroy my datatable and call the function that loads a new one:
$("#btnNewDatatable").click(function (){
destroy_data_table();
new_data();
});
And this is the function that reloads the datatable:
function new_data(){
var table = $('#example').DataTable({
"sAjaxSource": //Here I return in json what my server sends,
"fnServerData": function ( sSource, aoData, fnCallback, oSettings ){
oSettings.jqXHR = $.ajax({
"dataType": 'json',
"type": "POST",
"url": sSource,
"data": aoData,
"success": function(result){
fnCallback(result);
}
});
},
responsive: true,
'columnDefs': [{
'targets': 0,
'searchable':false,
'orderable':false,
'width':'1%',
'className': 'dt-body-center',
'render': function (data, type, full, meta){
return '<input type="checkbox">';
}
}]
});
}
My problem is that when loading the new databale, and when selecting a row, this continues to show me the data from the previous datatable, I made a console.log a var rows_selected = []; Which is in charge of storing the data of each selected row, I am badly destroying the table or what could be my mistake?
have you tried
keep this table variable as global for ease.
//Initialize First time
var table = $('#example').DataTable({
......
}
function destroy_data_table(){
table.clear().draw();
}
instead of destroy.
I have a page which loads multiple tables separated by TAB using bootstrap.
In the third tab called patient tab, I have an action being done inside a modal.
An ajax call in the view will call an action in controller, when the logic successfully returned to the view, it will call an alert box and to load the latest result set in the table, I put location.reload() function, HOWEVER, the page returns or load in the first TAB and not in the 3rd where I do some action.
Can I specify or force the Tab to be loaded?
here the snippet of the ajax call in view, since it is quite long
}).promise().done(function () {
$.ajax({
type: 'POST',
url: '/Patient/SaveWeight',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(add_upd_obj_arr),
dataType: "json",
traditional: true,
success: function (result) {
if (result.errMsg == '' || result.errMsg == "") {
bootbox.alert({
size: "small",
title: "Confirmation!",
message: "Successfully Updated.",
callback: function () {
$('#ModalVitalSign').modal('hide');
location.reload();
}
});
} else {
bootbox.alert(result.errMsg);
}
},
error: function () {
bootbox.alert({
size: "small",
title: "Error!",
message: "There is an error while loading data."
});
}
});
});
I tried this, but does not refresh
window.location.hash = tab_treatment_info; //id of the third tab
How to use dataTables to instantiate the table does not load data (server mode),then loading data when i click on a button.If serverSide is set to true at initialization, the table will automatically send an ajax request, then render the data, which is not what I want !:(
You should use "iDeferLoading" : 0 in DataTables parameters, when you initialize it:
var table = $("#table").dataTable({
"bProcessing": true,
"bServerSide": true,
"iDeferLoading": 0,
"sAjaxSource": service_url,
"sServerMethod": "POST",
...
...
(or "deferLoading":0 for newer DataTables versions, 1.10 and above),
and then add the event to your button:
$("#button").on("click", function (event) {
$('#table').dataTable().fnDraw();
});
https://datatables.net/examples/server_side/defer_loading.html
in a similar situation, this is how I did it.
<script>
$(function ($) {
$("#tbl").DataTable({columns:[{data:"id"}, {data:"text"}], dom: "tB", buttons: [{ text: "Load Me", action: function (e, dt, node, config) { loadme(e, dt, node, config); } }] });
}
);
// // parameters are passed from the datatable button event handler
function loadme(e, dt, node, config) {
parms = JSON.stringify({ parm1: "one", parm2: "two" });
$.ajax({
// my test web server that returns an array of {id:"code field", text:"country namee"}
url: "WebService1.asmx/GetAList",
data: JSON.stringify({ s: parms }),
type: 'post',
contentType: "application/json; charset=utf-8",
dataType: "json",
// this is just away of passing arguments to the success handler
context:{dt:dt, node:node},
success: function (data, status) {
var contries = JSON.parse(data.d);
for (var i = 0; i < contries.length; i++){
this.dt.row.add(contries[i], "id", "text");
this.dt.draw();
}
},
error: function (one, two) {
debugger;
}
});
}
</script>
</head>
<body>
<div style="width:500px">
<table id="tbl">
<thead>
<tr>
<th>Code</th>
<th>Contru</th>
</tr>
</thead>
<tbody></tbody>
<tfoot></tfoot>
</table>
</div>
</body>
After looking at the source code for half a day, I finally found a solution. First I needed a custom parameter called firstAjax and set it to false. like this:
$("#example").DataTable({
serverSide: true,
ajax: {
url: 'your url'
},
firstAjax: false
});
Then I changed the
_fnReDraw (settings); //in datatables.js line 4717
to
if (settings.oInit.firstAjax) {
_ fnReDraw (settings);
}
If the compressed js file(datatables.min.js), you should find _fnReDraw function corresponding alias.
I found the solution, in the initialization make like this, with the "oLanguage":
$('.table').dataTable({
oLanguage: {
sUrl: ""
}
});
After initialize datatables with ajax, use this simple line to call ajax for get data:
$('#table').DataTable().ajax.reload();
this code may not working with old versions of datatables.
Download latest version: https://datatables.net/download
I'm trying to get the remote using json from one php page,the JSON data:
[{"id":"0","name":"ABC"},{"id":"1","name":"DEF I"},{"id":"2","name":"GHI"}]
and the script is like this:
$(document).ready(function() {
$('#test').select2({
minimumInputLength: 1,
placeholder: 'Search',
ajax: {
dataType: "json",
url: "subject/data_json.php",
data: function (term, page) {// page is the one-based page number tracked by Select2
return {
college: "ABC", //search term
term: term
};
},
type: 'GET',
results: function (data) {
return {results: data};
}
},
formatResult: function(data) {
return "<div class='select2-user-result'>" + data.name + "</div>";
},
formatSelection: function(data) {
return data.name;
},
initSelection : function (element, callback) {
var elementText = $(element).attr('data-init-text');
callback({"name":elementText});
}
});
});
It works fine but it always reads the database whenever I typed one new character to search
. So i decided to use the another way (retrieve all data at first time and use select2 to search it):
$(document).ready(function() {
$("#test").select2({
createSearchChoice:function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term)===0; }).length===0) {
return {id:term, text:term};}
},
multiple: false,
data: [{"id":"0","text":"ABC"},{"id":"1","text":"DEF I"},{"id":"2","text":"GHI"}]
});
});
But the problem is how can I pass a request to data_json.php and retrieve data from it?
Say
data: $.ajax({
url: "subject/data_json.php",
data: function (term, page) {// page is the one-based page number tracked by Select2
return {
college: "ABC", //search term
};
}
dataType: "json",
success: function(data){
return data
}
}
But its not working, can anyone help?
Thanks
Why did you move away from your original code?
minimumInputLength: 1
Increase this and the search won't be called on the first character typed. Setting it to 3 for example will ensure the ajax call isn't made (and the database therefore not queried) until after the 3rd character is entered.
if I understood your question correctly you have data_json.php generating the options for select2 and you would like to load all of them once instead of having select2 run an ajax query each time the user inputs one or more characters in the search.
This is how I solved it in a similar case.
HTML:
<span id="mySelect"></span>
Javascript:
$(document).ready(function () {
$.ajax('/path/to/data_json.php', {
error: function (xhr, status, error) {
console.log(error);
},
success: function (response, status, xhr) {
$("#mySelect").select2({
data: response
});
}
});
});
I've found that the above does not work if you create a <select> element instead of a <span>.