How can I refresh the datatable after loading a dynamic content from an Ajax request? The flow is this,
1. a button will be click and this button contains an ID
2. I'll use this ID to do an Ajax request to the server
3. The server will reply the record from the passed ID
4. I'll load clear the initialized datatable and load the new content from the Ajax
5. Show bootstrap modal.
Now my problem is the header column and the content row of the datatable does not fit as shown below
The weird thing about this is when I resize my browser the header column fits with the table content.
Below is my code for this
<table id="mytable" class="cell-border" cellspacing="0" width="100%">
<thead class="table-header">
<tr>
<th>Comptetitor Item ID</th>
<th>Competitor Seller</th>
<th>Competitor Title</th>
<th>Competitor Price</th>
<th>Competitor Quantity Sold</th>
<th>Competitor Listing Status</th>
</tr>
</thead>
</table>
table1 = $('#mytable').DataTable({
scrollY : "250px",
scrollCollapse : true,
fixedColumns : false,
paging : false,
searching : false,
bInfo : false,
bSort : false,
});
$(document).on("click", ".a_tag_link",function() {
var row_id = $(this).data("row_id");
$.ajax({
type:'GET',
url:'/ajax/server_process',
dataType: 'json',
data: {
_token: "{{ csrf_token() }}",
view_id: $(this).data("row_id")
},
beforeSend: function() {
$.blockUI({ baseZ: 9999 });
},
success:function(response){
table1.rows().remove().draw();
$("#mymodal").modal("show");
table1.rows.add(response.data).draw(true);
},
complete: function(){
$.unblockUI();
}
});
return false;
});
Kindly help me with this. I just want the column header content to fit the table content without the browser being resized.
Updates: The table is fixed when I remove the scrollY attribute. But the problem is that the content is very large and I need the table to have a fix height
Try waiting for the modal to fully load, and then append the data. Probably, the datatable holder is not visible yet, and did not get its final dimensions:
success:function(response){
table1.rows().remove().draw();
$("#mymodal").modal("show");
setTimeout(function() {
table1.rows.add(response.data).draw(true);
},250);
},
You could also listen to modal's custom events, and draw the datatable when the modal has finished its animation:
success:function(response){
table1.rows().remove().draw();
$("#mymodal").modal("show");
table1.rows.add(response.data);
},
...
$('#myModal').on('shown.bs.modal', function (e) {
$('#mytable').DataTable().draw(true);
})
Related
I'm trying to get data from Database then append it in table columns using ajax jquery calls. Once i get the data and add it to the Datatable i lose the Datatable functionality which is normal since i'm dynamically adding data and i have to reinitialize the plugin. But the problem is whenever i initialize it i get and error stating "DataTables warning: table id=leadsListTable - Cannot reinitialize DataTable". I went to the link and applied every step they stated, yet i still get an error !
Here's my The HTML
<div class="table-responsive">
<table class="table invoice-data-table dt-responsive nowrap" id="leadsListTable" style="width:100%">
<thead>
<tr>
<th></th>
<th></th>
<th><span class="align-middle">Client#</span></th>
<th>Name</th>
<th>Phone</th>
<th>Adresse</th>
<th>Source</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody id="leadsList">
</tbody>
</table>
</div>
Here's the Ajax function call
function showAllClients(){
$.ajax({
type: 'ajax',
url: '<?php echo base_url() ?>leads/showAllClients',
async: false,
dataType: 'json',
success: function(data){
console.log(data)
var html ='';
for(i=0;i < data.length;i++){
html += '<tr>'+
'<td></td>'+
'<td></td>'+
'<td>'+data[i].lead_ID+'</td>'+
'<td>'+data[i].lead_Name+'</td>'+
'<td>'+data[i].lead_Phone+'</td>'+
'<td>'+data[i].lead_Adresse+'</td>'+
'<td>'+data[i].lead_Source+'</td>'+
'<td>'+data[i].lead_Status+'</td>'+
'<td>Edit</td>'+
'</tr>';
}
$('#leadsList').html(html);
$("#leadsListTable").dataTable({ //Tried this still getting the same error
"destroy": true,
});
},
error: function(){
alert('Could not get Data from Database');
}
});
}
Note that i did read other posts but either the solutions are outdated or they cause the same errors again. Please help !
I think that the problem might be that you destroy the datatable but never reinitialize it.
// Destroy the table
// Use $("#leadsListTable").DataTable().destroy() for DataTables 1.10.x
$("#leadsListTable").dataTable().fnDestroy()
// Reinitialize
$("#leadsListTable").dataTable({
// ... skipped ...
});
See if this works for you.
The Problem: When I click on a pagination link the script is generating the new html table content, but it's not refreshing the table in the browser.
I have class user with method called showUsers($limit, $offset) which is fetching all the data I need and displaying it in table.
<table id="table" class="table table-striped table-bordered table-hover table-sm">
<thead class="thead-default">
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Nickname</th>
<th>User ID</th>
</tr>
</thead>
<?php $user->showUsers($limit, $offset); ?>
</table>
this is my offset varaible: $offset = ($page - 1) * $limit, $page is the number of the pressed pagination link.
This is how I generate the pagination links:
<div class="col-sm-9 mx-auto">
<?php
for ($i=1; $i <= $allPages ; $i++) {
echo "<span class='pag-link' id='$i' style='cursor: pointer; padding: 6px; border: 1px solid #ccc; margin: 3px;'>". $i. "</span>";
}
?>
</div>
This is my JS Script:
//pagination-link handler.
$('.pag-link').click(function(){
var page = $(this).attr("id");
console.log(page);
$.ajax({
type: "POST",
url: "info.php",
data: {page: page},
success: function(data){
console.log(data); // show response from the php script.
}
});
});
setInterval(function(){ $(`#table`).load('info.php #table'); }, 1000);
Note: setInterval(function(){ $("#table").load('info.php #table'); }, 1000); should get the HTML in the table and update the table in the browser with the new table.
So when I click, a page the number is send in the info.php file. This changes my $offset variable and the showUsers($limit, $offset) method will generate new table with different data.
Now this is working because I'm seeing all new HTML that is generated in the javascript console, but setInterval(function(){ $("#table").load('info.php #table'); }, 1000); is not working and my table is not update.
Note: I want to refresh the table in interval, because if multiple users input data I want it to be updated to everyone in real time.
.load('info.php #table') doesn't have the page parameter.
So you load the page ("info.php"), click the next pagination link (url: "info.php",data: {page: page}), and that works, but then the timer loads info.php again, replacing the data.
This will require moving the "var page;" to the top of the Javascript, outside the function call:
//pagination-link handler.
var page=1;
$('.pag-link').click(function(){
page = $(this).attr("id");
console.log(page);
$.ajax({
type: "POST",
url: "info.php",
data: {page: page},
success: function(data){
console.log(data); // show response from the php script.
}
});
});
setInterval(function(){ $(`#table`).load('info.php?page='+page+'#table'); }, 1000);
The PHP that fills $offset will need to respond to both GET and POST, such as $_REQUEST.
I want to update table data without refreshing the page using Ajax and Jquery.
I know I will need setInterval() method, because I want the table to be refreshed to all users, because multiple users could insert data in to the database and I want to update the table to every user.
I have made a script to send the data from a form without redirecting the user or refreshing the page and then insert it in the database.
MyScript.js
$( document ).ready(function() {
console.log( "Ready!" );
//Submitting from data
$("#submitForm").submit(function(e){
if($('#fName').val() && $('#lName').val() && $('#nickname').val()) {
$.ajax({
type: "POST",
url: "process.php",
data: $("#submitForm").serialize(),
success: function(data){
console.log(data); // show response from the php script.
}
});
}
else {
alert("Please fill the fields.")
}
e.preventDefault();
});
});
In my process.php file I insert the data to the database.
Now I have info.php file that generates my table with all the data and I have a form there to insert new data.
<div id="table" class="col-md-7 ml-5">
<table class="table table-striped table-bordered table-hover table-sm">
<thead class="thead-default">
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Nickname</th>
<th>User ID</th>
</tr>
</thead>
<?php $user->showUsers(); ?>
</table>
</div>
the showUsers() function just generate the other rows of the table with the data from SQL.
I have no idea how to refresh the table using Jquery and Ajax.
I tried to use the .load() method, but it also generates the html for my form.
Please help.
As you said, you can use setInterval or better setTimeout since you want the return of the data to trigger a new request later
var tId="";
function getInfo() {
$.get("info.php #table",function(data) {
tId = setTimeout(getInfo,60000);
$("#someContainer").append(data);
});
}
getInfo();
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>
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 :(
Change this:
$(".changeStatus").on("change", function(){
var status = $('.changeStatus').val();
alert(status);
// e.t.c...
});
To this:
$(".changeStatus option").change(function(){
var status = $(this).val();
$.ajax({
url: "<?= SITE_URL . 'toplevel/update-data'; ?>",
method: "POST",
data: { statusChange : status },
success: function(data){
alert(status);
}
});
});
Hope it helps!
I'm trying to use Mustache.js but while my table is being created is not applying the Boostrap class properly. Only the header gets the css. I tried applying the class with jquery after the button click but did not help. I also try embedding the template inside the table but id did not work.
I have this html.
<table id="mTable" class="table table-striped">
<tr>
<th>FY</th>
<th>COST</th>
</tr>
</table>
then my template
<script id="priceTemplate" type="text/template">
<tr>
<td>{{FY}}</td>
<td>{{COST}}</td>
</tr>
</script>
my Ajax code.
$('#cmdSubmit').on('click', function () {
event.preventDefault();
var PriceTemplate = $('#priceTemplate').html();
$priceTable = $('#mTable');
$.ajax({
type: "GET",
url: "mywebservice.asmx/GetData",
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function (msg) {
var pricedata = eval(msg.d);
$.each(pricedata, function (i, price) {
$priceTable.append(Mustache.render(PriceTemplate, price));
});
}
});
});
my table is showing data but is looks like the template is not getting stylized by bootstrap.
TIA,