Jquery Ajax Datatable - javascript

var ownDataTable = $(".own_cases_table").dataTable();
$.ajax({
url : "api/v1/cases/"+encodeURIComponent(uid)+"/active",
type : "get",
headers : { "Authorization" : api_key },
dataType : "json",
success : function(response) {
if (response.error) {
} else {
var cases = response.cases;
ownDataTable.fnClearTable();
for (var i = 0; i < cases.length; i++) {
console.log(cases[i].case_name);
ownDataTable.fnAddData([ cases[i].case_name, cases[i].slide_img, 'Daha Fazla', 'action' ]);
}
}
}
});
HTML :
<!-- TABLE FOR MOBILE START -->
<table class="table mb30 own_cases_table">
<thead>
<tr>
<th><?php echo _("Olgu"); ?></th>
<th><?php echo _("Dijital Slide"); ?></th>
<th><?php echo _("Daha Fazla"); ?></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<!-- TABLE FOR MOBILE END -->
<div class="table-responsive hidden-xs hidden-sm">
<table class="table own_cases_table">
<thead>
<tr>
<th><?php echo _("Olgu"); ?></th>
<th><?php echo _("Dijital Slide"); ?></th>
<th><?php echo _("Daha Fazla"); ?></th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
i am using datatables but no data is added in datatables. Always writes "No data avaliable in table"
i checked cases has data and i $(".own_cases_table").DataTable(); but nothing changed.
How i can add data into my tables ?
I tried with ownDataTable.row.add() but same result occured

You can use this to initalize datatable.
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "../server_side/scripts/server_processing.php"
} );
from https://datatables.net/examples/data_sources/server_side.html

Related

Display Updated table without refreshing or reloading page

I have a table which shows the list of my products and I have used jQuery to delete products without reloading the page, however the updated table doesn't show unless I refresh the page..
I have tried to hide it by using opacity, still it doesn't work..
Here is my php code
<div class="table-stats order-table ov-h">
<table id="bootstrap-data-table" class="table ">
<thead>
<tr>
<th>Image</th>
<th>Name</th>
<th>Availability</th>
<th>Category</th>
<th>Total Ordered</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody id="data-table">
<?php
$stmt_1 = mysqli_prepare($link,"SELECT * FROM products");
mysqli_stmt_execute($stmt_1);
$result = mysqli_stmt_get_result($stmt_1);
while($row = mysqli_fetch_array($result)){ ?>
<div class="product">
<tr class="product">
<?php
$sql_img = "SELECT * FROM pro_images WHERE pro_id= ? LIMIT ?";
$stmt_img = mysqli_prepare($link, $sql_img);
mysqli_stmt_bind_param($stmt_img, "ii" ,$param_pro_id, $param_limit);
$param_pro_id = $row["pro_id"];
$param_limit = 1;
mysqli_stmt_execute($stmt_img);
$img_results = mysqli_stmt_get_result($stmt_img);
$image = mysqli_fetch_assoc($img_results);
?>
<td><img src="../admin/assets/img/products/<?php echo $image["pro_image"]; ?>"></td>
<td><?php echo $row["pro_name"]; ?></td>
<td><?php echo $row["pro_quantity"]; ?></td>
<?php
$sql_category = "SELECT cat_name FROM categories WHERE cat_id = ?";
$stmt_category = mysqli_prepare($link, $sql_category);
mysqli_stmt_bind_param($stmt_category, "i", $param_cat_id);
$param_cat_id = $row["pro_category"];
mysqli_stmt_execute($stmt_category);
$result_category = mysqli_stmt_get_result($stmt_category);
$category = mysqli_fetch_assoc($result_category);
?>
<td> <?php echo $category["cat_name"]; ?> </td>
<?php
$pro_ord = "SELECT COUNT(*) AS total FROM order_details WHERE pro_id = ?";
$pro_stmt = mysqli_prepare($link, $pro_ord);
mysqli_stmt_bind_param($pro_stmt ,"i", $row["pro_id"]);
mysqli_stmt_execute($pro_stmt);
$pro_res = mysqli_stmt_get_result($pro_stmt);
$pro = mysqli_fetch_array($pro_res);
?>
<td><?php echo $pro["total"]; ?></td>
<td><span class="badge badge-success"><i class="ti-pencil"></i></span>
</td>
<td>
<button class="remove badge badge-danger" onclick="delete_data(<?php echo $row["pro_id"]; ?>)"><i class="ti-trash"></i></button>
</td>
</tr>
</div>
<?php } ?>
</tbody>
</table>
</div>
And here is my JQUERY code
function delete_data(d){
    var id=d;
if (confirm("Are you sure you want to delete this product? This cannot be undone later.")) {
 $.ajax({
      type: "post",
      url: "products.php",
      data: {id:id},
      success: function(){
        $(this).parents(".product").animate("fast").animate({ opacity : "hide" }, "slow");
      }
    });
}
  }
And here is the delete code
$pro_id =$_POST['id'];
$delete = "DELETE FROM products WHERE pro_id= ?";
$results = mysqli_prepare($link, $delete);
mysqli_stmt_bind_param($results, "i", $param_pro_id);
$param_pro_id = $pro_id;
mysqli_stmt_execute($results);
You need to be more specific when you targeting the div you want to refresh, for example:
success: function(){
$("#div_id_you_want_refresh")
.load("your_entire_url" + "#div_id_you_want_refresh");
}
You can pass this as well inside your delete_data function where this refer to current element clicked i.e : your button . Then , inside success function use this to hide your .product element.
Demo Code:
function delete_data(d, el) {
var id = d;
if (confirm("Are you sure you want to delete this product? This cannot be undone later.")) {
/* $.ajax({
type: "post",
url: "products.php",
data: {
id: id
},
success: function() {*/
//use this then remove closest product tr
$(el).closest(".product").animate("fast").animate({
opacity: "hide"
}, "slow");
/* }
});*/
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="bootstrap-data-table" class="table">
<thead>
<tr>
<th>Image</th>
<th>Name</th>
<th>Availability</th>
<th>Category</th>
<th>Total Ordered</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody id="data-table">
<tr class="product">
<td><img src="../admin/assets/img/products/"></td>
<td>
smwthing
</td>
<td>
1
</td>
<td>
abs
<td>
1222
</td>
<td><span class="badge badge-success"><i class="ti-pencil"></i></span>
</td>
<td>
<!--pass `this` inside fn-->
<button class="remove badge badge-danger" onclick="delete_data('1',this)"><i class="ti-trash">x</i></button>
</td>
</tr>
<tr class="product">
<td><img src="../admin/assets/img/products/"></td>
<td>
smwthing
</td>
<td>
12
</td>
<td>
abs1
<td>
12221
</td>
<td><span class="badge badge-success"><i class="ti-pencil"></i></span>
</td>
<td>
<button class="remove badge badge-danger" onclick="delete_data('2',this)"><i class="ti-trash">x</i></button>
</td>
</tr>
</tbody>
</table>

Toggle button print double value

I have had toggle button name is Enable, Disable in my table and in which if
I change the value of a button Enable to Disable then it prints Disable value two times.
My code:
<table id="prodcutTable" class="table table-bordered table-striped" style="width: 100%;" >
<thead>
<tr style="font-size: 12px; line-height: 0px; ">
<th>SR No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email ID</th>
<th>Phone Number</th>
<th>Status</th>
<th></th>
</tr>
<?php $counter=1?>
<?php foreach($result as $result):?>
<tr>
<input type="hidden" name="txt_user_id" value="<?php echo $result['id']?>">
<td><?php echo $counter?></td>
<td><?php echo $result['username']?></td>
<td><?php echo $result['lastname']?></td>
<td><?php echo $result['email']?></td>
<td><?php echo $result['phonenumber']?></td>
<td>
<?php
if ($result['status']=="active"){
?>
<span class="badge badge-boxed badge-soft-success">Active</span>
<?php
}else if($result['status']=="inactive"){
?>
<span class="badge badge-boxed badge-soft-warning">InActive</span>
<?php
}
?>
</td>
<td>
<input type="checkbox" class="btn-toggle" name="toggle" id="toggle" data-toggle="toggle" data-off="Disabled" data-on="Enabled" <?php
if($result['status']=="active") echo "checked"; ?> >
</td>
</tr>
<?php $counter++?>
<?php endforeach;?>
</thead>
</table>
<script>
function disableUser(id) {
$.ajax({
url: "<?php echo base_url(); ?>admin_controller/AdminController/disableUser",
method: "post",
data: {id:id},
dataType:'json',
})
.done(function( data ) {
if(data.status=="true"){
alert('Enabled');
setTimeout(function(){location.reload();},100);
}else{
alert("Try Again");
}
});
}
function enableUser(id) {
$.ajax({
url: "<?php echo base_url(); ?>admin_controller/AdminController/enableUser",
method: "post",
data: {id:id},
dataType:'json',
})
.done(function( data ) {
if(data.status=="true"){
alert('Disabled');
setTimeout(function(){location.reload();},100);
}else{
alert("Try Again");
}
});
}
$('.btn-toggle').change(function(){
var tr = $(this).parents('tr');
//console.log(tr);
var txt_user_id = tr.find($('input[name="txt_user_id"]')).val();
//console.log(txt_user_id);
var mode= $(this).prop('checked');
console.log(mode);
if($(this).prop('checked'))
{
enableUser(txt_user_id);
}
else
{
disableUser(txt_user_id);
}
});
</script>
I do not know where I wrote the wrong code in my code.
Following is the image of my table on how to look like a toggle bar.
And the color also changes to blue to white.
put this code in your ready function :
$('.btn-toggle').bootstrapToggle({
on: 'Enabled',
off: 'Disabled'
});

Codeigniter ajax status code shows 200 but display error message

Just try to make it simple.
I'm trying to show data in my data table when I click a dropdown value
I'm using ajax to get the data from my controller
everything works fine except the results isn't showing in my view even the status code shows 200 ok
here's my Model
function tampil_renja(){
$this->db->distinct();
$this->db->select
(
'lkp_program.progskpd_id AS prog_id,
CONCAT(msr_mstrurusan.uru_kode, '.', lkp_program.progskpd_kode) AS prog_kode,
lkp_program.progskpd_prog_uraian as prog_uraian');
$this->db->from('msr_mstrurusan');
$this->db->join('lkp_program', 'msr_mstrurusan.uru_id = lkp_program.progskpd_ursid');
$this->db->join('lkp_kegiatan', 'lkp_program.progskpd_id = lkp_kegiatan.kegskpd_prog_id');
$this->db->join('mnv_keg_renja', 'lkp_kegiatan.kegskpd_id = mnv_keg_renja.tar_keg_id');
$this->db->where('mnv_keg_renja.tar_keg_id is NOT NULL', NULL, FALSE);
$this->db->order_by("lkp_program.progskpd_id", "asc");
return $this->db->get();
}
here's my ajax code within the view
<div class="container-fluid">
<header>
<h3 class="mb-2">Renja</h3>
</header>
<div class="card-body">
<div class="table-responsive" style="margin-bottom: 1px;">
<?php
if (count($skpd) > 0) {
?>
<label class="col-sm-1 control-label">OPD</label>
<div class="col-sm-5">
<select id="skpd" name="skpd" class="form-control input-sm">
<option value="0">-- Pilih Perangkat Daerah--</option>
<?php
foreach ($skpd as $pd) {
echo "<option value='" . $pd->uk_kowil . "#" . $pd->uk_id . "'>" . strtoupper($pd->uk_nama) . "</option>";
}
?>
</select>
</div>
<?php
}
else {
?>
<input type='hidden' name='skpd' id='skpd' value='<?php
?>' />
<?php
}
?>
<div id="listskpd" class="col-sm-1">
<i id="rldspin" style="margin-top:5px"></i>
</div>
<div id="jml_angg" class="text-right" style="padding-top: 8px;font-size: 13px;margin-right: 15px;">
</div>
</div>
<table id="list_target" class="table table-striped table-bordered table-hover" width="100%">
<thead>
<tr>
<th rowspan="3" class="text-center text-middle" style="width:1%;">No</th>
<th rowspan="3" class="text-center text-middle" style="width:4%;">Kode Rekening</th>
<th rowspan="3" class="text-center text-middle" style="width:27%;">Program/Kegiatan</th>
<th rowspan="3" class="text-center text-middle" style="width:20%;">Indikator Kinerja program (outcome)/ kegiatan (output) </th>
<th colspan="7" class="text-center text-middle" style="width:30%;">Target Renja [berdasarkan DPA] SKPD pada Tahun</th>
</tr>
<tr>
<th rowspan="2" class="text-center text-middle" style=""> Satuan</th>
<th colspan="2" class="text-center text-middle" style="">Target Triwulan 1</th>
<th colspan="2" class="text-center text-middle" style="">Target Triwulan 2</th>
<th colspan="2" class="text-center text-middle" style="">Target Triwulan 3</th>
<th colspan="2" class="text-center text-middle" style="">Target Triwulan 4</th>
<th rowspan="2" class="text-center text-middle" style="">Target Anggaran</th>
</tr>
<tr>
<th class="text-center text-middle" style="">Kin</th>
<th class="text-center text-middle" style="">Keu</th>
<th class="text-center text-middle" style="">Kin</th>
<th class="text-center text-middle" style="">Keu</th>
<th class="text-center text-middle" style="">Kin</th>
<th class="text-center text-middle" style="">Keu</th>
<th class="text-center text-middle" style="">Kin</th>
<th class="text-center text-middle" style="">Keu</th>
</tr>
</thead>
<tbody id="datatarget">
</tbody>
</table>
</div>
</div>
</article>
<script type="text/javascript" language="javascript" src="<?php echo base_url().'assets/vendor/jquery/jquery.js'?>"></script>
<script type="text/javascript" language="javascript" src="<?php echo base_url().'assets/vendor/datatables/jquery.dataTables.js'?>"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#skpd').change(function(){
var arrval = $(this).val().split("#");
var kowil = arrval[0];
var idpd = arrval[1];
if(idpd != 0){;
tampil_data_renja(kowil, idpd);
} else {
$('#datatarget').DataTable.Destroy();
$('#datatarget').DataTable.Draw();
$('#datatarget').DataTable.Destroy();
}
});
function tampil_data_renja(kowil, idpd){
$.ajax({
type : 'ajax',
url : '<?php echo base_url()?>renja/tampil_renja/',
async : false,
dataType : 'json',
success : function(data){
var html = '';
var i;
alert(data.length);
for(i=0; i<data.length; i++){
html += '<tr>'+
'<td>'+(i+1).toString()+'</td>'+
'<td>'+data[i].prog_kode+'</td>'+
'<td>'+data[i].prog_uraian+'</td>'+
'</tr>';
}
$('#datatarget').html(html);
},
error: function(){
alert('Could not load the data');
}
});
}
and this is the controller
function tampil_renja(){
echo json_encode( $this->m_data->tampil_renja()->result() );
}
JSON result in the network tab of chrome dev tools
[{"prog_id":"1","prog_kode":"6.01.0118","prog_uraian":"Program Koordinasi, pembinaan dan penyelenggaraan pemerintahan, ketentraman dan ketertiban umum, perekonomian, kesejahteraan sosial dan pembangunan"},{"prog_id":"2","prog_kode":"6.01.0118","prog_uraian":"Program Koordinasi, pembinaan dan penyelenggaraan pemerintahan, ketentraman dan ketertiban umum, perekonomian, kesejahteraan sosial dan pembangunan"}]
any help and guide would be appreciated
sorry for my bad english by the way
Please try the following code:
Changes made are:
commented datatype in the AJAX
parse response of success function as JSON.
$.ajax({
type : 'get', // edit 1
url : '<?php echo base_url()?>renja/tampil_renja/',
async : false,
//dataType : 'json', //change over here
success : function(data){
data = JSON.parse(data); //change over here
var html = '';
var i;
alert(data.length);
for(i=0; i<data.length; i++){
html += '<tr>'+
'<td>'+(i+1).toString()+'</td>'+
// '<td>'+data[i].prog_id+'</td>'+
'<td>'+data[i].prog_kode+'</td>'+
'<td>'+data[i].prog_uraian+'</td>'+
'</tr>';
}
$('#datatarget').html(html);
},
error: function(){
alert('Could not load the data');
}
})
You have to redraw the datatable after the element is updated on ajax call success :
//fungsi tampil barang
function tampil_data_renja(kowil, idpd){
// var requrl = '<?php echo base_url()?>renja/tampil_renja/'+kowil+'/'+idpd;
$.ajax({
type : 'ajax',
// url : '<?php echo base_url()?>renja/tampil_renja/'+kowil+'/'+idpd,
url : '<?php echo base_url()?>renja/tampil_renja/',
async : false,
dataType : 'json',
success : function(data){
var html = '';
var i;
// console.log(data.length);
alert(data.length);
for(i=0; i<data.length; i++){
html += '<tr>'+
'<td>'+(i+1).toString()+'</td>'+
// '<td>'+data[i].prog_id+'</td>'+
'<td>'+data[i].prog_kode+'</td>'+
'<td>'+data[i].prog_uraian+'</td>'+
'</tr>';
}
$('#datatarget').html(html);
$('#list_target').DataTable.Draw(); // redraw the datatable
},
error: function(){
alert('Could not load the data');
}
});
// return alert(kowil);
}

How to pass an javascript array to an php script

I have a normal html table filled with database entries.
I got a plugin to select multiple rows in this table.
Now i want to click on a button and delete the database entry so I need to get the id out of the array and but it in my php script.
But I have not really an idea how to do it.
</div>
<table id="myTable" class="content-table">
<thead>
<tr>
<th>ID</th>
<th>Artikelnummer</th>
<th>Name</th>
<th>Preis</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT * FROM artikel;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td> <?php echo $row["id"]?></td> <?php
?> <td> <?php echo $row["artikelnummer"]?></td> <?php
?> <td> <?php echo $row["name"]?></td> <?php
?> <td> <?php echo $row["preis"]?> €</td> </tr><?php
}
}
?>
</tbody>
</table>
</div>
var $rows = [];
$(function() {
console.log( "ready!" );
// start plugin
$('#myTable').TableSelection({
sort : true, // sort or not (true | false)
status : 'multiple', // single or multiple selection (default is 'single')
}, function(obj){ // callback function return selected rows array
$rows = obj.rows;
});
});
<?php
include_once 'dbh.inc.php';
$artid = ???;
$sql = "DELETE FROM artikel WHERE id= $artid;";
mysqli_query($conn, $sql);
header("Location: ../index.php?daten=success");
You can do it with html attributes. I make a example for you with html, css and javascript.
this is your html.
<table id="tableSelected" class="content-table">
<thead>
<tr>
<th>ID</th>
<th>Artikelnummer</th>
<th>Name</th>
<th>Preis</th>
</tr>
</thead>
<tbody>
<tr data-id="1">
<td>1</td>
<td>1-1</td>
<td>Test</td>
<td>1</td>
</tr>
<tr data-id="2">
<td>2</td>
<td>2-1</td>
<td>Foo</td>
<td>1</td>
</tr>
</tbody>
</table>
as you can see, every "tr" tag has "data-id" attribute.
var $rows = [];
$(function() {
$('#tableSelected').TableSelection({
sort : true,
status : 'multiple',
}, function(obj) {
$.each(obj.rows, function(i, row){
var id = $('#tableSelected').RowValue(row).attr('data-id') // You can get id with this code
});
});
});
Note: https://codepen.io/yusufilkeroguz/pen/vqPgzZ you can see live preview from here :)

Can not submit selected values in datatable

I am trying to implement multiple select checkboxes in datatable. But when I submit the form, I got this error
TypeError: table.column is not a function[Learn More]
I am using the following code:
pageSetUp();
var pagefunction = function() {
var table = $('#pendingInvoice').dataTable({
"sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6'f>
<'col-sm-6 col-xs-6 hidden-xs'T>r>"+"t"+
"<'dt-toolbar-footer'<'col-sm-6 col-xs-12
hidden-xs'i><'col-sm-6 col-xs-12'p>>",
"oLanguage": {
"sSearch": '<span class="input-group-addon">
<i class="glyphicon glyphicon-search"></i></span>'
},
"oTableTools": {
"aButtons": [
"copy",
"xls",
{
"sExtends": "pdf",
"sTitle": "Techmj_PDF",
"sPdfMessage": "Techmj PDF Export",
"sPdfSize": "A4"
},
{
"sExtends": "print",
"sMessage": "Generated <i>(press Esc to close)</i>"
}
],
"sSwfPath": "js/plugin/datatables/swf/copy_csv_xls_pdf.swf"
},
"columnDefs": [
{
'targets': 0,
'checkboxes': {
'selectRow': true
}
}
],
order: [[ 0, 'desc' ]],
'select': {
'style': 'multi'
}
});
$('#frm-example').on('submit', function(e){
e.preventDefault();
var rows_selected = table.column(0).checkboxes.selected();
$.each(rows_selected, function(index, rowId){
$(form).append($('<input>')
.attr('type', 'hidden')
.attr('name', 'id[]')
.val(rowId));
});
});
};
loadScript("js/plugin/datatables/jquery.dataTables.min.js", function(){
loadScript("js/plugin/datatables/dataTables.colVis.min.js", function(){
loadScript("js/plugin/datatables/dataTables.tableTools.min.js", function(){
loadScript("js/plugin/datatables/dataTables.bootstrap.min.js", function(){
loadScript("js/plugin/datatables/dataTables.checkboxes.min.js", function(){
loadScript("js/plugin/datatable-responsive/datatables.responsive.min.js", pagefunction);
});
});
});
});
});
Here is my html table:
<form id="frm-example" action="model/unapprove.php" method="POST">
<table id="pendingInvoice" class="table table-striped table-bordered table-hover" width="100%">
<thead>
<tr>
<th data-hide="phone">ID</th>
<th data-class="expand">Customer Name</th>
<th data-hide="phone,tablet">Group Name</th>
<th data-hide="phone,tablet">Pay Amount</th>
<th data-hide="phone,tablet">Pay Date</th>
<th data-hide="phone,tablet">Action</th>
</tr>
</thead>
<tbody>
<?php while($row = $app->fetch(PDO::FETCH_OBJ)): ?>
<tr>
<td><?php echo $row->id; ?></td>
<td><?php echo $row->hming; ?></td>
<td><?php echo $row->groupname; ?></td>
<td><?php echo $row->payamount; ?></td>
<td><?php echo $row->paydate; ?></td>
<td><?php if($row->status=='Approved'){
echo 'Approved';
}else if($row->status=='Pending'){
echo 'Pending';
}else{
echo 'Rejected';
} ?></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
<p><button type="submit" class="btn btn-success">Approve</button></p>
</form>
Where could the code go wrong? When I hit the submit button the it could not get the table variable. I could not figure it out where the code goes wrong. Please help.
Use DataTable() instead of dataTable() to initialize your table. For example:
var table = $('#pendingInvoice').DataTable({
// ... skipped ...
});
See jQuery DataTables Checkboxes for more examples and details.

Categories