DataTables row.add() not working Ajax Server side - php

I'm working on adding a new row in my datatable on button click. Here's my code:
HTML:
<table id="datatable-batches" class="table table-striped table-bordered forex-datatable">
<thead>
<tr>
<th>Batch #</th>
<th>Qty</th>
<th>Date</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Batch #</th>
<th>Qty</th>
<th>Date</th>
</tr>
</tfoot>
</table>
Script:
<script type="text/javascript">
var table;
$(document).ready(function() {
//datatables
var batches_table = $('#datatable-batches').DataTable({
"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
"order": [], //Initial no order.
"ajax": {
"url": "<?php echo site_url('oss/admin/ajax_batches'); ?>",
"type": "POST",
data: {
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
},
dataSrc: function ( json ) {
if(json.csrf_token !== undefined) $('meta[name=csrf_token]').attr("content", json.csrf_token);
return json.data;
}
}
});
$(function() {
$('#new-batch').on('click', function(){
$('#receiving-box').css('display', 'block');
batches_table.row.add( ["3", "5", "2017-06-24 08:55:41"] ).draw();
});
});
});
</script>
Both are in the same file. When I hit the button, only the 'draw' number is increased but the data is still the same.
I also copied and pasted the example table here to make sure row.add() is working. Here's the debugger data for additional info.
Any help is highly appreciated. Thanks!

Related

Datatable sorting not working properly after destroyed the table and recreate

I using Jquery to clear the table tbody and reinsert in via ajax call. after the data is showed, but the sorting function is not working properly. here is my codes..
<table class="table table-bordered table-striped table-condensed flip-content table-hover" style="table-layout:fixed;" id="datatable1">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
</tr>
</thead>
<tbody id="agtBody">
<?php
foreach($results as $result) :
?>
<tr>
<?php if(isset($game_name['gpname'])){?>
<td><?=$game_name['gpname']?></td>
<?php }else{ ?>
<td><?=$result['gpid']?></td>
<?php } ?>
<td style="text-align:right;"><?=Helper::money($result['betAmt'])?></td>
<td style="text-align:right;"><?=Helper::money($result['payout'])?></td>
<td style="text-align:right;"><?=Helper::money($result['winLoss'])?></td>
<td style="text-align:right;"><?=Helper::money($result['validbetamount'])?></td>
</tr>
<?php endforeach; ?>
</tbody>
<tfoot id ="agtFoot">
<tr style="background-color:#FFEEDD;">
<td>Total</td>
<td style="text-align:right;"><?=Helper::money($totalbetAmt)?></td>
<td style="text-align:right;"><?=Helper::money($totalpayout)?></td>
<td style="text-align:right;"><?=Helper::money($totalwinLoss)?></td>
<td style="text-align:right;"><?=Helper::money($totalvalidbetamount)?></td>
</tr>
</tfoot>
</table>
<script type="text/javascript">
function search_agtdetail(agentcode) {
if($("#agt_StartTime").val() == "" || $("#agt_EndTime").val() == "") {
alert("<?php echo 'Not Valid' ?>");
} else {
$("#agtBody").empty();
$("#agtFoot").empty();
$.ajax({
type: "post",
url: "/report/agentBoxAjax",
dataType: "json",
data: {
start_date: $("#agt_StartTime").val(),
end_date: $("#agt_EndTime").val(),
agent_code : agentcode,
},
success: function (data) {
$('#datatable1').dataTable().fnDestroy();
$('#agtBody').html(data.html);
$('#agtFoot').html(data.html_foot);
$('#datatable1').css('width', '');
$('#datatable1').dataTable({
'bPaginate':false,
'bSort': true,
});
}
});
}
}
$(document).ready(function(){
$('#datatable1').dataTable({
'bPaginate':false,
'bSort': true,
});
});
</script>
Can someone help me? The sorting is not working properly..
Its look like using the old data for sorting it.
i had less experience on jquery, someone please help. Thank you so much.
Extending on Bhushan Kawadkar comment you need to use the API method for this.Also you should be using the ajax methods for your datatable.
For example, lets say that i get the server side data from a script called data.php, i would just call it like this:
$('#datatable1').dataTable({
'bPaginate':false,
'bSort': true,
"ajax": {
"url": "data.php",
"type": "GET"
}
});
the post.php needs to return the data in json format like this (using car as example):
{
"data":[
[
"Ford",
"Fiesta",
"2015"
],
]
}
in your success section in the ajax call instead of destroying the table just use:
$('#datatable1').ajax.reload()
Here's a snippet just in case.
$(document).ready(function() {
var table = $('#example').DataTable({
"ajax": 'https://raw.githubusercontent.com/DataTables/DataTables/master/examples/ajax/data/arrays.txt',
});
$("#reload_table").on("click",function(){
console.log("reloading data");
table.ajax.reload();
});
});
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<html>
<body>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Profession</th>
<th>City</th>
<th>Date</th>
<th>Salary</th>
</tr>
</thead>
</table>
</body>
<input id="reload_table" type="button" value="RELOAD TABLE">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
</html>

Get dataTable data using ajax

I am trying to display dataTable data using ajax but it didn't work.
This is my jquery code :
$('#example').DataTable({
ajax: {
type: 'GET',
url: 'data.php',
success: function (msg) {
$("#tbody_example").html(msg);
}
}
});
This is my data.php page :
<?php echo '<td>Name</td>
<td>Position</td>
<td>Office</td>
<td>Extn.</td>
<td>Start date</td>
<td>Salary</td>'; ?>
and This is my dataTable :
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tbody id="tbody_example">
</tbody>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
My dataTable still empty and I get MOCK GET: data.php as error.
Any one can help me.
That will not work.
Please, reference DataTables documentation to see that success must not be overridden as it is used internally in DataTables.
Instead you might use function ajax( data, callback, settings )
$('#example').DataTable({
ajax: function(data, callback, settings) {
$.get({
type: 'GET',
url: 'data.php',
success: function (msg) {
$("#tbody_example").html(msg); // this is NOT how the table should be populated
// invoke callback(msg) to populate the table
});
}
});
Thus, you populate the table by calling callback(response_data) with the response_data that is either string[][] or object[] type. In case of the latter you might need to add "columns" property to DataTables config.
It works for me.I just add dataType
ajax: {
type: 'GET',
url: 'data.php',
dataType : 'html',
success: function (msg) {
$("#tbody_datatable").html(msg);
},
error: function (req, status, err) {
console.log('Something went wrong', status, err);
}
}
Try the below thing, It should work
In php file
$content = "<td>Name</td>
<td>Position</td>
<td>Office</td>
<td>Extn.</td>
<td>Start date</td>
<td>Salary</td>";
$return["json"] = json_encode();
echo json_encode($return);
In ajax
ajax: {
type: 'GET',
url: 'data.php',
success: function (msg) {
$("#tbody_example").html(msg["json"]);
}
}

Datatable not working on ajax call

I use Datatable in my web application.
Following is my simple code to get data using ajax.
<script>
$(document).ready(function() {
$('#mytable').DataTable();
} );
</script>
<body>
<h2>AJAX SELECT</h2><hr>
<div align="center">
Select Team :
<select name="select" id ='teamSelect'>
<option value="">Select Value</option>
<option value="op2">Company 1</option>
</select>
</div>
<div id='tableContainer' align="center"></div>
<script>
$(function() {
$("#teamSelect").bind("change", function() {
$.ajax({
type: "GET",
url: "getData.php",
"dataSrc": "tableData",
success: function(html) {
$("#tableContainer").html(html);
}
});
});
});
</script>
and Getdata.php Code
<table id="mytable" class="display" cellspacing="0" width="50%">
<thead>
<tr>
<th>First name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>Airi Satou</td>
<td>Accountant</td>
<td>Tokyo</td>
</tr>
<tr>
<td>Brielle Williamson</td>
<td>Integration Specialist</td>
<td>New York</td>
</tr>
<tr>
<td>Herrod Chandler</td>
<td>Sales Assistant</td>
<td>San Francisco</td>
</tr>
<tr>
<td>Rhona Davidson</td>
<td>Integration Specialist</td>
<td>Tokyo</td>
</tr>
</tbody>
I Link Jquery, datatable css and js both.but still It return output as normal HTML table.
No console error founded.
I need that data in datatable. So how can i get that.
and i also tested datatable in index.php page. It working quite good.
You are initializing datatable before table added. You need to initialize it in ajax
remove following script
<script>
$(document).ready(function() {
$('#mytable').DataTable();
} );
</script>
update ajax as below:
<script>
$(function() {
$("#teamSelect").bind("change", function() {
$.ajax({
type: "GET",
url: "getData.php",
"dataSrc": "tableData",
success: function(html) {
$("#tableContainer").html(html);
$('#mytable').DataTable({
"destroy": true, //use for reinitialize datatable
});
}
});
});
});
</script>
Put
<script>
$(document).ready(function() {
$('#mytable').DataTable();
} );
</script>
At the bottom of your Getdata.php file also links to the datatable css and js.
Or use ajaxComplete function() to call the datatable.

DataTables Server side and Slim Framework

I've been working on datatables server side processing and slim framework and I always get this error in my browser:
When I check chrome developer tools, I am seeing this in the console:
Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:8000/user/ssp-data.php?draw=1&columns%5B0%5D%5Bdata%5D=0&c…art=0&length=10&search%5Bvalue%5D=&search%5Bregex%5D=false&_=1440509303609
My html code is here:
<table id="dataTableUsers" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>ID</th>
<th>Nickname</th>
<th>Email</th>
</tr>
</thead>
<tfoot>
<tr>
<th>ID</th>
<th>Nickname</th>
<th>Email</th>
</tr>
</tfoot>
</table>
My script:
$(document).ready(function() {
$('#dataTableUsers').dataTable( {
"processing": true,
"serverSide": true,
"ajax": "ssp-data.php"
} );
} );
ssp.data.php
http://pastebin.com/iBnWgAHd
I successfully used datatables but not server side processing. It loads 1000+ rows for about 5 seconds and I don't want my client to wait every time like that. I tried searching and found that datatables server side processing can be helpful. What have I done wrong with my code? Thank you in advance.
Using slims Framework 3, you need to have 2 routes for this, the first one:
$app->get('/datatable-example',function(){
... // your html code goes here
});
is for rendering the HTML page, the '/datatable-example' could be changed into whatever you want. The second route:
$app->get('/datatable-data',function(){
... // your server-side handler goes here
});
is for returning the data. The 'datatable-data' could be changed but it must be consistent with the JS code below:
$(document).ready(function() {
$('#dataTableUsers').dataTable( {
"processing": true,
"serverSide": true,
"ajax": "datatable-data"
});
});
notice that the value of "ajax" is also "datatable-data", the same as the second route.
I'll copy the whole example below, but it's kinda dirty and hacky, but it should work when you copy to your route file:
$app->get('/datatable-example',function(){
return
'
<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script></head>
<head><script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script></head>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css" />
<table id="dataTableUsers" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>ID</th>
<th>Nickname</th>
<th>Email</th>
</tr>
</thead>
<tfoot>
<tr>
<th>ID</th>
<th>Nickname</th>
<th>Email</th>
</tr>
</tfoot>
</table>
<script>
$(document).ready(function() {
$("#dataTableUsers").dataTable( {
"processing": true,
"serverSide": true,
"ajax": "/datatable-data"
} );
} );
</script>
';
});
$app->get('/datatable-data',function(){
return
'{
"draw": 1,
"recordsTotal": 2,
"recordsFiltered": 2,
"data": [
["1", "Nick" ,"nick#mail.com"],["2", "John" ,"john#mail.com"]
]
}';
});
hope it helps.

Datatables not loading

I am trying to using datatables Jquery plugin in codeingiter but its not working please help me to debug
Heres my controller where I am calling my view:
public function show_all_merchants()
{
$data["query"]= $this->details_model->get_mids();
$this->load->view('show_merchants_view',$data);
}
Heres my view:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="<?php echo base_url(); ?>assets/js/jquery.dataTables.js"></script>
<script>
$(document).ready(function()
{
$('#example').dataTable
({
'bProcessing' : true,
'bServerSide' : true,
'sAjaxSource' : 'show_merchant_details',
'iDisplayStart' : 0,
'fnServerData': function(sSource, aoData, fnCallback)
{
$.ajax
({
'dataType': 'json',
'type' : 'POST',
'url' : sSource,
'data' : aoData,
'success' : fnCallback,
'cache' : false
});
}
});
});
</script>
<table cellpadding="0" cellspacing="0" border="0" id="example">
<thead>
<tr>
<th width="20%">ID</th>
<th width="25%">First Name</th>
<th width="15%">Last Name</th>
<th width="25%">Email</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="5">Loading data from server</td>
</tr>
</tbody>
</table>
and heres my controller where I am loading the data Here I am loading data tables library:
function show_merchant_details()
{
$this->datatables
->select('mid, merchant_name, merchant_link,merchant_contact')
->from('merchants')
->add_column('edit', 'Edit', 'id')
->add_column('delete', 'Delete', 'id');
echo $this->datatables->generate();
}
Friends show_merchant_details() is wrking properly as i am able to see the output
In the view page I am able to see it like Loading data from server ...... (dats it)

Categories