reload datatable after ajax success - javascript

I use JQuery DataTable. I send data to datatable onclick in json file at ajax succes .the first click everything is good,But the next click I get only the right data ANd wrong value of dataTables_info it display always the first value of dataTables_info And paginatio AND row too from the first result.
This is the first display of data in datatable:
ALL the next Click I get only right data:
For this exemple they are one result showing in picture below but everything else(info ,show,pagination) belong to first search showing in the first picture :
In the second Exemple When I click at any page of pagination I get the content of the first page result!!
This is my function ONclick:
$ ( '#ButtonPostJson' ).on('click',function() {
$("tbody").empty();
var forsearch = $("#searchItem").val();
$.ajax({
processing: true,
serverSide: true,
type: 'post',
url: 'searchData.json',
dataType: "json",
data: mysearch,
/* bRetrieve : true,*/
success: function(data) {
$.each(data, function(i, data) {
var body = "<tr>";
body += "<td>" + data.name + "</td>";
..........................
..........................
body += "</tr>";
$('.datatable-ajax-source table').append(body);
})
;
/*DataTables instantiation.*/
$('.datatable-ajax-source table').dataTable();
},
error: function() {
alert('Processus Echoué!');
},
afterSend: function(){
$('.datatable-ajax-source table').dataTable().reload();
/* $('.datatable-ajax-source table').dataTable({bRetrieve : true}).fnDestroy();
$(this).parents().remove();
$('.datatable-ajax-source table').dataTable().clear();*/
}
});
});
I try everything and i dont know what I miss.
I use this jquery for datatable:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>
Thanks.

Use like it
$('#product_table').DataTable().ajax.reload();

Get table id first, like:
var table=('#tableid').Datatable();
table.draw();
just put these lines after ajax success function to reload datatable

On a button clik you dont need to empty your table body and make initiate the datatable again with the ajax.
you just have to call your ajax again as you have already initiate on document ready function
just use
$("#Table_id").ajax.reload();
check the below link, you will have better idea.
https://datatables.net/reference/api/ajax.reload()
Let me know if this doesn't help you

I had this same problem. I found a function I wrote on a project that deals with this. Here is a simple 2 column table I made.
<table id="memberships" class="table table-striped table-bordered table-hover" width="100%">
<thead>
<tr>
<th>Member Name</th>
<th>Location</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Member Name</th>
<th>Location</th>
</tr>
</tfoot>
</table>
This is my script to populate it:
function drawTable(){
var table = $('#memberships').DataTable();
table.destroy();
value = $("#memberName").val();
console.log("member name-->>" + value);
$('#memberships').DataTable({
responsive:true,
pageLength: 50,
ajax:{
"url": `//BACKEND API CALL`,
"type":"get",
"dataSrc": 'members'//my data is in an array called members
},
columns: [
{"data": "name_display" },
{"targets": 0,
"data": "membershipID",
"render": function ( data, type, full, meta ) {
return '<button type="button" class="btn btn-info btn-block"
onclick="editMember(' + data + ')">Edit Member</button><button
type="button" class="btn btn-danger btn-block"
onclick="deleteMember(' + data + ')">Delete</button>';
}
}
]
});
$.fn.dataTable.ext.errMode = 'none';
}
You can ignore my column render function. I needed 2 buttons based on the data returned. The key was the table.destroy in the function. I created the table in a variable called table. I destroy it right in this initialization because it allowed me to use this same function over and over. The first time it destroys an empty table. Each call after that destroys the data and repopulates it from the ajax call.
Hope this helps.
Update: After playing with datatables alot more I found that setting table to a variable in a global scope to your function allows you to use reload.
var table = $('#memberships').DataTable({});
Then
table.ajax.reload();
should work.

I created this simple function:
function refreshTable() {
$('.dataTable').each(function() {
dt = $(this).dataTable();
dt.fnDraw();
})
}

use below code..it perfectly work, it keep your pagination without lose current page
$("#table-example").DataTable().ajax.reload(null, false );

$('.table').DataTable().ajax.reload();
This works for me..

$("#Table_id").ajax.reload(); did not work.
I implemented -
var mytbl = $("#Table_id").datatable();
mytbl.ajax.reload;

.reload() is not working properly untill we pass some parameter
var = $("#example").DataTable() ;
datatbale_name.ajax.reload(null, false );

Try This i hope it will work
$("#datatable_id").DataTable().ajax.reload();

Related

jQuery Datatables Reload

I'm facing an issue using the Datatables plug-in regarding a table reload after the user adds a row.
I'm receiving some JSON data as part of a webservice call, after successfully receiving that data, I am calling a function that will build the table rows and append them to the tbody of the datatable as follows:
const buildTableRows = obj => {
const table = document.querySelector('#participantes tbody');
table.innerHTML = "";
for (item of obj) {
const tableRow = `<tr id="${item.ContactoId}" data-contributos="${item.Contributos}" data-updated="false" class="participante-row"><td><i class="material-icons">arrow_right</i>${item.Nome}</td><td class="contributos"><input value="${item.Contributos}">&nbsp&nbsp&nbsp<i class="material-icons delete">delete_forever</i></td></tr>`;
table.insertAdjacentHTML('beforeend', tableRow);
}
}
After this, I call another function responsible for initializing the Datatable and saving it to a global object for future reference:
const buildDataTable = () => {
const table = $('#participantes').DataTable({
"pagingType": "simple_numbers",
"pageLength": 4,
"lengthChange": false,
"columnDefs": [{
"targets": 1,
"orderable": false
}],
responsive: true
});
controlObj.datatable = table;
}
In my HTML I have a dynamically generated select element which lets the user add a row to the table. When the user adds the row, those two functions get called again. I can see the new row in my data structure but the table doesn't get refreshed without a page reload. I went through the plugin docs and tried to use the destroy method, rows.add(), clear(), draw() etc.. but nothing seems to work for me. The table structure is already in the DOM, I just need to reload the table. Any help would be much appreciated
Datatable cannot be clear and redraw for updated HTML DOM for table but it has to be inserted using JSON array.
To refresh it after change in DOM, you need to destroy the table and re-initalize it.
See below example where on click of ADD button I have added new row and reiniitalized the table but before that I have destroyed it.
$(document).ready(function() {
//Initialize the table and save it in a variable.
var table = $('#example').DataTable();
var id = 0;
$('#add').on('click', function(){
table.destroy();
//add row to the table
var html = '<tr><td>' + id + '</td><td>First Name' + id + '</td><td>Last Name' + id + '</td></tr>';
//console.log(html);
$('#example tbody').append(html);
id++;
table = $('#example').DataTable();
});
} );
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/dataTables.jqueryui.min.css">
<script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<table id="example" class="display nowrap" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>First name</th>
<th>Last name</th>
</tr>
</thead>
<tbody>
<tr>
<td>00</td>
<td>First</td>
<td>Last</td>
</tr>
</tbody>
</table>
Click Button to Add row : <input id="add" value=" ADD " type="button">
Yes you can use DataTable api. without destroying table you just need a function.
$(document).ready(function() {
var dt = $('#example').DataTable();
$('#addRow').click(function () {
var rowHtml = $("#newRow").find("tr")[0].outerHTML
console.log(rowHtml);
dt.row.add($(rowHtml)).draw();
});
});
here is working example

How to redraw a Datatable that uses server side processing using only the existing data in the datatable?

I'm trying to delete a row from a Datatable that uses server side processing (removing the row data and the row/tr visually) based on the value of certain attribute of the row.
I'm using the remove() function to do it and it removes the row data, but visually the table stills the same.
So I added the draw() function but it reinitializes the table, including the data.
So, how can I "redraw" the table after removing a row from the Datatable that uses server side processing? Is there any other function like draw() to redraw the table but using only the existing data in the datatable?
$("#tableSelector").DataTable()
.rows( function ( idx, data, node ) {
return data.attribute_value == value_to_delete;
} )
.remove()
.draw();
Finally, I found the solution.
I followed this thread then read about the DataTable's property "dataSrc".Then with this information searched for something similar in Stack Overflow and found this.
So the trick to do what I asked for was to use a variable to filter the row which I want to ignore in the ajax call.
I've reused the code provided in the referred question. And this is the result:
HTML:
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Subject</th>
<th>Status</th>
<th>Message</th>
<th>Details</th>
</tr>
</thead>
</table>
JS:
$(document).ready(function() {
function loadDataTable(excluded_name = undefined){
$("#example").DataTable().destroy();
$('#example').DataTable({
// "processing" : true,
"ajax" : {
"url" : "https://api.myjson.com/bins/12uwp2",
"dataSrc": (json) => {
if(excluded_name !== undefined){
return json.filter((item) => item.name !== excluded_name)
}else{
return json
}
}
},
"columns" : [ {
"data" : "name"
}, {
"data" : "email"
}, {
"data" : "subject"
}, {
"data" : "status"
},{
"data" : "message"
},
{
"mData": "Details",
"mRender": function (data, type, row) {
return "<a class='delete' data-name='"+ row.name + "' data-id=" + row.id + " href='/Details/" + row.id + "'>Delete</a>";
}
}]
});
}
$(document).on("click", ".delete", function(e) {
e.preventDefault()
let excluded_name = $(this).data("name")
alert("Excluding this name in the next load: " + excluded_name);
loadDataTable(excluded_name);
})
loadDataTable();
});
Fiddle: https://jsfiddle.net/ek94mh1x/4/
Note: This is a client side "delete", I know this could be done with server side processing, but in my case I was only allowed to do it in the client side.
Additionally, in case you need to delete multiple rows you could use an array as a parameter and follow the same logic.
I hope this could help someone.

How to get value from html select tag option value using onChange event using jQuery data table?

I am working on jQuery Data table to load few data from mysql database.
Here is the html code :
<table id="employee-grid" cellpadding="0" cellspacing="0" border="0" class="display" width="100%">
<thead>
<tr>
<th>#</th>
<th>User Id</th>
<th>Address</th>
<th>Package Name</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
</table>
From php page I'm loading the data like bellow :
// skipping more code...
$nestedData[] = "
<select class='form-control changeStatus' name='status'>
<option value=''>--Select--</option>
<option value='1|$client_id' $statusMsg1>Active</option>
<option value='2|$client_id' $statusMsg2>Blocked</option>
</select>";
Now the loaded data is look like this :
Now I want to call the an Ajax request when html selected option value is change. It's calling Ajax request successfully by bellow code.
jQuery code for jQuery Data Table and My Ajax Request :
$(document).ready(function() {
var dataTable = $('#employee-grid').DataTable( {
"processing": true,
"serverSide": true,
"ajax":{
url :"server_processing.php", // json datasource
type: "post", // method , by default get
error: function(){ // error handling
$(".employee-grid-error").html("");
$("#employee-grid").append('<tbody class="employee-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
$("#employee-grid_processing").css("display","none");
}
}
} );
$("#employee-grid").on('change', function() {
var status = $('.changeStatus').val();
alert(status);
$.ajax({
url : "<?php echo SITE_URL . 'toplevel/update-data'; ?>",
data : {
'statusChange' : status
},
type : 'POST',
});
});
});
but When I select the option then every time it's passing first option value
For e.g. This selected option tag has these value :
<option value='1|11' $statusMsg1>Active</option>
<option value='2|11' $statusMsg2>Blocked</option>
It's always passing 1|11 value !! It's should be pass my selected option value. I don't understand why it's happening :(
Note : I think using jQuery data table custom jquery code should be use in different way.
Well Guys,
I have solved it. I need to use something like that :
$('#employee-grid').on('change', '.changeStatus', function(){
// testing.....
var status = $('.changeStatus').val();
alert(status);
});
The solution is to use event delegation by providing selector for target element as a second argument in on() call.

how to populate a html table inside a dynamically loaded DIV

i have a DIV container inside a HTML page where I am dynamically loading other HTML pages using jquery.load() function . On one of the pages i need to populate a table from the database just after/before that page loads. How do I call a javascript function that executes just after that DIV is loaded with the page.
this is the dynamically loaded "headquarters.html" page:
<div class="row">
<div class="col-md-10" >
<table class="table table-bordered table-hover" id="tbl_hqlist">
<tr>
<th> HQ Code</th>
<th> Headquarter Name</th>
</tr>
</table>
</div>
</div>
i am loading that page using jquery.load() function like below:
function fn_headquarters(){
$('#bodyContent').load("../html/headquarters.html");
headquarterManagement();
return;
}
function headquarterManagement(){
$.ajax({
url:"../bin/manage_hq.php",
data:{ 'procAction': 1},
method: 'POST',
dataType: 'JSON',
success: function(proc_msg){
// get data and populate the table using jquery.each() & jquery.append() functions
},
error: function(xhr){
console.log(xhr.responseText);
}
})
return;
}
this code fails to update "tbl_hqlist".
jQuery load() uses AJAX and is therefore asynchronous, lucky for you, it provides a callback parameter. Adjust like so...
function fn_headquarters(){
$('#bodyContent').load("../html/headquarters.html", function(){
headquarterManagement();
});
return;
}
By doing this, you will make sure the element actually exists before populating it.
?Bonus: This will create table markup from json data:
function makeTableFromArray(arrayOfData){
var html_buffer = [];
html_buffer.push("<table><thead><tr>");
var headerData = arrayOfData[0];
for(var p in headerData)
if(headerData.hasOwnProperty(p))
html_buffer.push("<th>"+p+"</th>");
html_buffer.push("</tr></thead><tbody>");
for(var i=0; i<arrayOfData.length; i++){
html_buffer.push("<tr>");
for(var p in arrayOfData[i])
if(arrayOfData[i].hasOwnProperty(p))
html_buffer.push("<td>"+arrayOfData[i][p]+"</td>");
html_buffer.push("</tr>");
}
html_buffer.push("</table>");
return html_buffer.join("");
}
https://jsfiddle.net/sbctwdLc/

Put a button in front of all rows in jQuery DataTables

I am using jQuery DataTables. It is being populated with JSON data from a database. I can't figure out how to display a button or link in front of each record. I want to make it so that when the user clicks on that button then that particular record gets added in the database, so the button or link should contain an ID. Please help sort out my problem.
Below is the code I'm using:
var oTable = $('#jsontable').dataTable();
$.ajax({
url: 'process.php?method=fetchdata',
dataType: 'json',
success: function(s) {
console.log(s);
oTable.fnClearTable();
for (var i = 0; i < s.length; i++) {
oTable.fnAddData([
s[i][3],
s[i][4],
s[i][0], // this contains id
]);
}
},
error: function(e) {
console.log(e.responseText);
}
});
<table id="jsontable" class="display table table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Class Number</th>
<th>Subject</th>
<th>ADD</th>
</tr>
</thead>
</table>
I hope this is help
oTable = $('#jsontable').dataTable({
"fnRowCallback": function (nRow, aaData, iDisplayIndex) {
//nRow Row Object
//aaData Param
//iDisplayIndex Row Index
$('td:eq(0)', nRow).html("<input type='button'>Button</input>");
return nRow;
}
});
Do you mean to do something like this? (Also, this may be for an older version of datatables, now that I think about it. This is syntax for version 1.9, and I would guess you're using a more recent version (1.10+) The syntax may be a little different, but it should be documented in the api docs.
$('#jsontable').dataTable({
"sAjaxSource" : "process.php?method=fetchdata",
"aoColumns" : [
{ "mData": function(source) {
return '<input type="button" value=' + source[0] + '/>';
}},
{ "mData": function(source) {
return source[1];
}},
{ "mData": function(source) {
return source[2];
}}
}
});
Obviously, your button can look however you want, you probably don't want the id stored on the value. You can do what you need with it.

Categories

Resources