I have index.html and ajax.php with detail code in below
index.html
<div >
<!-- Table -->
<table id='empTable' class='display dataTable'>
<thead>
<tr>
<th>Employee name</th>
<th>Email</th>
<th>Gender</th>
<th>Salary</th>
<th>City</th>
<th>Action</th>
</tr>
</thead>
</table>
</div>
<!-- Script -->
<script>
$(document).ready(function(){
$('#empTable').DataTable({
'processing': true,
'serverSide': true,
'serverMethod': 'post',
'ajax': {
'url':'ajaxfile.php'
},
'columns': [
{ data: 'emp_name' },
{ data: 'email' },
{ data: 'gender' },
{ data: 'salary' },
{ data: 'city' },
{ data: 'action' },
]
});
});
</script>
</body>
ajaxfile.php
$empQuery = "select * from employee WHERE 1 ".$searchQuery." order by ".$columnName." ".$columnSortOrder." limit ".$row.",".$rowperpage;
$empRecords = mysqli_query($con, $empQuery);
$data = array();
while ($row = mysqli_fetch_assoc($empRecords)) {
$data[] = array(
"emp_name"=>$row['emp_name'],
"email"=>$row['email'],
"gender"=>$row['gender'],
"salary"=>$row['salary'],
"city"=>$row['city'],
"action"=><a class='btn btn-xs btn-warning' href='user_edit.php?uid='".$row['id']."'; '>
<i class='fa fa-pencil'></i> Ubah Data
</a>
);
}
## Response
$response = array(
"draw" => intval($draw),
"iTotalRecords" => $totalRecords,
"iTotalDisplayRecords" => $totalRecordwithFilter,
"aaData" => $data
);
echo json_encode($response);
then im trying to put action button "user_edit" using my usual method but not working. However if me put action"=>row['id']; the code is working fine. My question is how to put action button with value from row['id']; . Thank you
try this one, your action should be an String. Inside the class you can add something like delete-button. And remove the href or remove the link and just add a number sign like href="#", since you are working with ajax. We dont want to go to other page.
$data[] = array(
"emp_name"=>$row['emp_name'],
"email"=>$row['email'],
"gender"=>$row['gender'],
"salary"=>$row['salary'],
"city"=>$row['city'],
"action"=>"<a class='btn btn-xs btn-warning delete-button'
uid='".$row['id']."'; '><i class='fa fa-pencil'></i> Ubah Data</a>"
);
and then in yout html file or js file, you can create an event for that specific button that has a class of delete-button.
$('.delete-button').on('click',function(){
//get the id by
var = $(this).attr('uid');
//functions here
$.post('http://ajaxfile.php').then(function(res){
//reload the datatables
$('#empTable').DataTable.draw();
});
});
for more details explanation you can watch this videos.
https://www.youtube.com/results?search_query=jquery+datatables+server-side+processing+
Try this way
write action in variable and assign that variable to array action
while ($row = mysqli_fetch_assoc($empRecords)) {
$action = "<a class='btn btn-xs btn-warning' href='user_edit.php?uid='".$row['id']."'; '>
<i class='fa fa-pencil'></i> Ubah Data
</a>";
$data[] = array(
"emp_name"=>$row['emp_name'],
"email"=>$row['email'],
"gender"=>$row['gender'],
"salary"=>$row['salary'],
"city"=>$row['city'],
"action"=>$action;
);
}
Related
So I tried this tutorial : https://mbahcoding.com/tutorial/php/codeigniter/codeigniter-ajax-crud-modal-server-side-validation.html
and my data shows like this : image of how the data & the features looks
I just want to show the table and using the search feature on the green sign in the picture. But, when I follow the tutorial, there is some features showing (ex : red & blue sign in the picture).
Where I can change to remove the red feature in the picture and move the blue sign feature in the picture to the green sign?
I am still learning at how ajax works. Sorry if my explanation is too complicated. But, I hope you understand... Hope you can help me...
This is the function that I use at my Model - detkelModel.php:
var $table = 'detail_keluarga';
var $column_order = array('nama', 'hubungan', 'personilid', 'lahir', null); //set column field database for datatable orderable
var $column_search = array('nama', 'hubungan', 'personilid', 'lahir'); //set column field database for datatable searchable just nama, hubungan, personilid, lahir are searchable
var $order = array('id' => 'desc'); // default order
private function _get_datatables_query()
{
$this->db->from($this->table);
$i = 0;
foreach ($this->column_search as $item) // loop column
{
if ($_POST['search']['value']) // if datatable send POST for search
{
if ($i === 0) // first loop
{
$this->db->group_start(); // open bracket. query Where with OR clause better with bracket. because maybe can combine with other WHERE with AND.
$this->db->like($item, $_POST['search']['value']);
} else {
$this->db->or_like($item, $_POST['search']['value']);
}
if (count($this->column_search) - 1 == $i) //last loop
$this->db->group_end(); //close bracket
}
$i++;
}
if (isset($_POST['order'])) // here order processing
{
$this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
} else if (isset($this->order)) {
$order = $this->order;
$this->db->order_by(key($order), $order[key($order)]);
}
}
function get_datatables()
{
$this->_get_datatables_query();
if ($_POST['length'] != -1)
$this->db->limit($_POST['length'], $_POST['start']);
$query = $this->db->get();
return $query->result();
}
function count_filtered()
{
$this->_get_datatables_query();
$query = $this->db->get();
return $query->num_rows();
}
public function count_all()
{
$this->db->from($this->table);
return $this->db->count_all_results();
}
This is my View of the table and the searchbar - detkel.php:
<div class="navbar navbar-expand navbar-white navbar-light">
<!--left navbar / Data Keluarga label-->
<div class="col-sm-6 float-left">
<h5>Data Keluarga Personil</h5>
</div>
<!-- Right navbar links -->
<ul class="navbar-nav ml-auto">
<!-- Navbar Search, filter, plus data -->
<li class="nav-item">
<div class="form-inline">
<div class="input-group" data-widget="search-bar">
</div>
</div>
</li>
<!-- Filter Dropdown Menu -->
<li>
</li>
<!-- Plus data dropdown menu -->
<li>
<a class="btn btn-default" data-toggle="dropdown" href="#">
</a>
<div class="dropdown-menu dropdown-menu-lg dropdown-menu-right">
</div>
</li>
</ul>
</div>
<div class="card">
<div class="table-responsive p-0">
<table id="table" class="table table-hover text-nowraps">
<thead>
<tr>
<th>Nama</th>
<th>id personil</th>
<th>Hubungan</th>
<th>Tanggal Lahir</th>
<th>Aksi</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
This is the script in my view
<script type="text/javascript">
var save_method; //for save method string
var table;
$(document).ready(function() {
//datatables
table = $('#table').DataTable({
"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
"order": [], //Initial no order.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('DetkelController/ajax_list') ?>",
"type": "POST"
},
//Set column definition initialisation properties.
"columnDefs": [{
"targets": [-1], //last column
"orderable": false, //set not orderable
}, ],
});
});
</script>
This is ajax_list() in my Controller DetkelController.php:
public function ajax_list()
{
$list = $this->dk->get_datatables();
$data = array();
//$no = $_POST['start'];
foreach ($list as $dk) {
//$no++;
$row = array();
$row[] = $dk->nama;
$row[] = $dk->hubungan;
$row[] = $dk->personilid;
$row[] = $dk->lahir;
//add html for action
$row[] = '<a class="btn btn-sm btn-primary" href="javascript:void(0)" title="Edit" onclick="edit_person(' . "'" . $dk->id . "'" . ')"><i class="glyphicon glyphicon-pencil"></i> Edit</a>
<a class="btn btn-sm btn-danger" href="javascript:void(0)" title="Hapus" onclick="delete_person(' . "'" . $dk->id . "'" . ')"><i class="glyphicon glyphicon-trash"></i> Delete</a>';
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->dk->count_all(),
"recordsFiltered" => $this->dk->count_filtered(),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
I am trying to make single page application with jquery using php i have created page which have 3 events inserts update and delete after each event data also be re fetched to display on table with new data but now the problem happening is when data be re fetched it not let events to work again like there are two button on every row of data edit and delete. but once you edit first row it not let you edit any other row. there must be way to make it but what could be solution i am newbie with jquery.
Here is my jquery.
$( document ).ready(function() {
// When click the button.
$("#save").on('click',function() {
// Assigning Variables to Form Fields
var category = $("#catname").val();
if(category){
$.ajax({
type: "post",
url: "insert.php",
asynch: false,
data: {
"category": category
},
success: function(data){
alert("Category Saved Successfully. ");
$("#ecname").html("");
$("#show").html(data);
$( '#form_category' ).each(function(){
this.reset();
});
}
});
}
else{
$("#ecname").html("fill category name");
}
});
});
Here is html of table.
<div class="m-portlet m-portlet--mobile">
<div class="row" id="categories">
<?php
$i = 1;
$categories = $obj->getallcategories();
echo '
<div class="col-lg-12">
<div class="m-portlet__body">
<table class="table table-striped- table-bordered table-hover table-checkable" id="m_table_1">
<thead>
<tr>
<th>
Id
</th>
<th>
category Name
</th>
<th>
category Name
</th>
<th>
Edit
</th>
<th>
Delete
</th>
</tr>
</thead>
<tbody id="show">
';
foreach($categories as $category){
echo'
<tr>
<td>'.$i.'</td><td>'.$category['cname'].'</td>
<td>categories</td>
<td><button value="'.$category['cid'].'" class="btn btn-primary get" id="get'.$category['cid'].'">edit </button></td>
<td><button class="btn btn-danger" id="del'.$category['cid'].'" value="'.$category['cid'].'" type="button">Delete</button></td>
</tr>
';
$i++;
}
?>
</tbody>
</table>
</div>
</div>
</div>
Here is insert.php page which return data on ajax call of #save button click.
<?php
include("../functions/backend.php");
$obj = new Crud();
if(isset($_POST['category']))
{
$cname = $_POST['category'];
$obj->addcategory($cname);
$i = 1;
$categories = $obj->getallcategories();
foreach($categories as $category){
echo'
<tr>
<td>'.$i.'</td><td>'.$category['cname'].'</td>
<td>categories</td>
<td><button value="'.$category['cid'].'" class="btn btn-primary get" id="get'.$category['cid'].'">edit </button></td>
<td><button class="btn btn-danger" id="del'.$category['cid'].'" value="'.$category['cid'].'" type="button">Delete</button></td>
</tr>
';
$i++;
}
}
else {
echo "<script>alert('Something went wrong')</script>";
}
?>
edited with new self function which i want to make delegate.
function removeitem() {
var cid = $("[id^=del]").val();
$.ajax({
type: "post",
url: "delete.php",
asynch: false,
data: {
"cid": cid
},
success: function(data){
$("#show").html(data);
}
});
}
$("[id^=del]").confirm({
text: "Are you sure you want to delete ?",
confirm: function(button) {
//removeitem();
},
cancel: function(button) {
// nothing to do
},
confirmButton: "Yes I am",
cancelButton: "No",
post: true,
confirmButtonClass: "btn-danger",
cancelButtonClass: "btn-default",
dialogClass: "modal-dialog modal-lg" // Bootstrap classes for large modal
});
You need to read about event-delegation.
Delegated event handlers have the advantage that they can process
events from descendant elements that are added to the document at a
later time. By picking an element that is guaranteed to be present at
the time the delegated event handler is attached, you can use
delegated events to avoid the need to frequently attach and remove
event handlers.
For example, you need to do it like this:
$('body').on('click','#mybutton', function(){
//code here..
});
I'm working on a project which uses Laravel 5.1 as the server side framework, I built a tables to show leads using jQuery Datatables plugin and yajrabox Datatables add-on for Laravel.
I am implementing a server side processing but I need to manipulate the data before send it to the client, for do this I need to first pull all the data i'd like to show (to manipulate it) which make the process really long.
this is the code i'm using:
public function index()
{
return view('leads.test')->with($data);
}
returns the view, and:
public function getLeads()
{
$end = new \MongoDate(Carbon::now()->endOfDay()->setTimezone(Client::getTimezone(5))->timestamp);
$start = new \MongoDate(Carbon::now()->subWeek()->startOfDay()->setTimezone(Client::getTimezone(5))->timestamp);
return \Datatables::of(collect($this->setLeadData(Lead::where('deleted',0)->where('client_id','5')->whereBetween('created_at',[$start,$end])->orderBy('created_at','desc')->get())))->make(true);
}
return the leads, and last one, the manipulation process:
private function setLeadData($leads)
{
$rtn = [];
$row = [];
foreach ($leads as $lead) {
$row['DT_RowId'] = $lead->_id;
if(\Auth::user()->canDeleteLeads()){
$row['checkbox'] = "<input type='checkbox' class='bulk-delete-leads-checkbox' name='bulk_delete_leads[]' id='".$lead->_id."' /><label for='".$lead->_id."'></label>";
}
if(Carbon::createFromFormat("Y-m-d H:i:s", $lead->created_at)->isSameDay(Carbon::now()->startOfDay())){
$row['date'] = "<i class='fa fa-clock-o'></i> at ".Carbon::createFromFormat("Y-m-d H:i:s", $lead->created_at)->timezone(Client::getTimezone())->format("H:i");
}else{
$row['date'] = "<i class='fa fa-clock-o'></i> ".Carbon::createFromFormat("Y-m-d H:i:s", $lead->created_at)->timezone(Client::getTimezone())->toDateTimeString();
}
if(is_array($lead->ga_details) && count($lead->ga_details) > 1){
$row['user_type'] = $lead->ga_details['user_type'];
$row['device_category'] = $lead->ga_details['device_category'];
$row['source'] = $lead->ga_details['source'];
$row['campaign'] = $lead->ga_details['campaign'];
$row['ad_group'] = $lead->ga_details['ad_group'];
$row['path'] = $lead->ga_details['path'];
}
$row['last_feed'] = null;
if ($lead->feeds && count($lead->feeds)) {
$row['last_feed'] = array_reverse($lead->feeds)[0]['message'];
}
$row['status'] = $this->setLeadStatusElement($lead->status,$lead->_id);
$row['owner'] = $this->setLeadOwnerElement($lead->owner,$lead->_id);
$data['has_reminder'] = false;
$icon = '';
$reminder = Notification::where('lead_id', $lead->_id)
->where('type', 'lead_reminder')
->where('due_time','<=',Carbon::now()->toDateTimeString())
->where('active',1)
->where('deleted',0)
->first();
if($reminder){
$data['has_reminder'] = true;
$icon = " <i class='fa fa-bell'></i> ";
}
$row['full_name'] = '<button type="button" class="btn btn-w-m btn-white single-lead-trigger" style="width:100%!important" data-toggle="modal" data-lead-id="' .$lead->_id. '" data-target="#single_lead">No Name'.$icon.'</button>';
if(isset($lead->the_lead) && count($lead->the_lead)){
foreach($lead->the_lead as $k => $lead_detail){
if($k == "full_name"){
$row['full_name'] = '<button type="button" class="btn btn-w-m btn-white single-lead-trigger" style="width:100%!important" data-toggle="modal" data-lead-id="' .$lead->_id. '" data-target="#single_lead">' .$lead_detail.$icon.'</button>';
}else{
$row[$k] = $lead_detail;
}
}
if(isset($lead->the_lead['full_name']) && !empty($lead->the_lead['full_name'])){
}
}
$rtn[] = $row;
}
return $rtn;
}
Does any one has any suggestion about how to do it right and proper? thank you very much for any answer! Appreciate it!!
here is my working example, that How I am using this.
My controller method for Datatable
public function getData()
{
$supplier = Supplier::with('manufacturer')->select(['id','proprietor','qualified_person','manufacturer_id','license_no','nth_registration_no','phone','mobile','email','address','status']);
return Datatables::of($supplier)
->editColumn('status', function($supplier){
return (($supplier->status == 1)?"Active":"Deactive");
})
->editColumn('phone', function($supplier){
return "Phone#: ".$supplier->phone." <br /> Mobile#: ".$supplier->mobile;
})
->editColumn('manufacturer_id', function($supplier){
//return $supplier->manufacturer->name;
if($supplier->manufacturer_id != 0){
return $supplier->manufacturer->name;
}else{
return 'Not selected!';
}
})
->addColumn('actions', '
<div class="btn-group">
<i class="fa fa-pencil"></i>
<a href="{!!route("ajax-delete",["type"=>"supplier","id"=>$id ])!!}" data-target="#ajax_delete" data-toggle="modal" class="btn btn-xs btn-danger">
<i class="fa fa-trash-o"></i>
</a>
</div>
')
->remove_column('mobile')
->make(true);
}
my View structure
<table class="table table-bordered table-striped table-condensed flip-content" id="supplier">
<thead class="flip-content">
<tr>
<th>Manufacturer</th>
<th>Qualified Person</th>
<th>Proprietor</th>
<th>License#</th>
<th>Reg#</th>
<th>Contact#</th>
<th>Email</th>
<th>Address</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
</table>
Datatable JS for server side processing
<script type="text/javascript">
var oTable;
$(document).ready(function() {
oTable = $('#supplier').DataTable({
"responsive": true,
"processing": true,
"serverSide": true,
"ajax": "{!!route('supplier-data')!!}",
"columns": [
{data: 'manufacturer_id', name: 'manufacturer_id'},
{data: 'qualified_person', name: 'qualified_person'},
{data: 'proprietor', name: 'proprietor'},
{data: 'license_no', name: 'license_no'},
{data: 'nth_registration_no', name: 'nth_registration_no'},
{data: 'phone', name: 'phone'},
{data: 'email', name: 'email'},
//{data: 'mobile', name: 'mobile'},
{data: 'address', name: 'address'},
{data: 'status', name: 'status'},
{data: 'actions', name: 'actions'},
]
});
});
</script>
here is the example of picking items from multiple laravel relationship.
public function getData()
{
$medicine = Medicine::with(['manufacturer','doseageForm','measureUnit','supplier'])
->select(['id','product_name','generic_name','product_class','manufacturer_id',
'doseage_form_id','measure_unit_id','strenght','status']);
return Datatables::of($medicine)
->editColumn('status', function($medicine){
return (($medicine->status == 1)?"Active":"Deactive");
})
->editColumn('manufacturer_id', function($medicine){
$manufacturer_name = $medicine->manufacturer->name;
return $manufacturer_name;
})
->editColumn('product_name', function($medicine){
return
$medicine->product_name.", ".
$medicine->doseageForm->name.", ".
$medicine->strenght.$medicine->measureUnit->name;
})
->addColumn('supplier',function($medicine){
if($medicine->supplier->count() > 0){
return $medicine->supplier->first()->qualified_person;
}else{
return '---';
}
})
->addColumn('actions', function($medicine){
$edit_route = route('medicine-edit',['id'=>$medicine->id ]);
$del_route = route("ajax-delete",["type"=>"medicine","id"=>$medicine->id ]);
$status = (($medicine->status == 1)?
'<i class="fa fa-eye"></i>'
:
'<i class="fa fa-eye-slash"></i>'
);
$html = '<div class="btn-group">
'.$status.'
<i class="fa fa-pencil"></i>
<a href="'.$del_route.'" data-target="#ajax_delete" alt="delete" data-toggle="modal" class="btn btn-xs btn-danger">
<i class="fa fa-trash-o"></i>
</a>
</div>';
return $html;
})
->make(true);
}
I'm using the jQuery DataTables plugin and within the initialization I'm using the "drawCallback" to make changes to the look of the rows.
My code is as follows:
"drawCallback": function() {
table.rows().every( function() {
var d = this.data();
var option = this.find('.options');
if (d.activated) {
option.html('<button class="btn btn-mini btn-primary pull-right"> Enabled</button>');
} else {
option.html('<button class="btn btn-mini btn-danger pull-right"> Disabled</button>');
}
});
}
However the this.find('.options') part isn't doing anything.
Essentially I want to:
get the current row
select the column I've given the className of 'options'
insert a button there relevant to the row data
HTML:
<table id="example">
<thead>
<tr>
<th></th>
<th>Last Name</th>
<th>First Name</th>
<th>Email</th>
<th></th>
</tr>
</thead>
</table>
DataTables initialisation:
var table = $('#example').DataTable( {
columns: [
{
"className": 'center',
"data": null,
"defaultContent": ''
},
{
data: 'last_name'
},
{
data: 'first_name'
},
{
data: 'email'
},
{
"className": 'options',
"data": null,
"defaultContent": ''
}
],
// ...and so on
Originally I had the following code which worked:
$('td.options').html('<button class="btn btn-mini btn-primary pull-right"> Enabled</button>');
but this was indiscriminate of the row data and simply pasted the same button for each row.
Use columns.render option to define a function producing content for the cell.
var table = $('#example').DataTable( {
columns: [
{
"className": 'center',
"data": null,
"defaultContent": ''
},
{ "data": 'last_name' },
{ "data": 'first_name' },
{ "data": 'email' },
{
"className": 'options',
"data": null,
"render": function(data, type, full, meta){
if (full.activated) {
return '<button class="btn btn-mini btn-primary pull-right"> Enabled</button>';
} else {
return '<button class="btn btn-mini btn-danger pull-right"> Disabled</button>';
}
}
}
],
// ...and so on
});
How can page through the results? .It With ajax.
to bring the data to my view , I want to use paginate () and orderby (), but to put it is in the documentation , it generates error.
if I do so : $cita= Cita::orderBy(asc)->paginate(10), I did not bring the data. Excuse the English 'm Mexican .
Controller:
public function agenda(){
$cita = Cita::all();
return Response()->json(
$cita->toArray()
);
}
Script:
function Carga(){
var tablaDatos = $("#datos");
var route = "http://cmec.app/agenda";
$("#datos").empty();
$.get(route, function(res){
$(res).each(function(key, value){
tablaDatos.append(
"<tr><td>"+value.name+"</td><td>"+value.lastname+"</td><td>"+value.doctor+"</td><td>"+value.fecha+"</td><td>"+value.hora+"</td><td><div class='btn-group btn-group-sm' role='group'><button value="+value.id+" OnClick='Mostrar(this);' class='btn btn-danger'><i class='fa fa-trash-o'></i></button><button value="+value.id+" OnClick='Mostrar(this); ' class='btn btn-primary' data-toggle='modal' data-target='#editar-modal' ><i class='fa fa-pencil-square'></i></button></div></td></tr>");
});
});}
Vista:
<table class="table table-hover">
<thead>
<tr>
<th>Nombre</th>
<th>Apellidos</th>
<th>Doctor</th>
<th>Fecha</th>
<th>Hora</th>
<th>Acciones</th>
</tr>
</thead>
<tbody id="datos"></tbody>
</table>
Use following for you code
Controller
public function agenda(){
$cita = Cita::orderBy('asc')->paginate(10);
return response()->json($cita->toArray());
}
Script
function Carga(){
var tablaDatos = $("#datos");
var route = "http://cmec.app/agenda";
$("#datos").empty();
$.getJson(route, function(res){
$(res).each(function(key, value){
tablaDatos.append(
"<tr><td>"+value.name+"</td><td>"+value.lastname+"</td><td>"+value.doctor+"</td><td>"+value.fecha+"</td><td>"+value.hora+"</td><td><div class='btn-group btn-group-sm' role='group'><button value="+value.id+" OnClick='Mostrar(this);' class='btn btn-danger'><i class='fa fa-trash-o'></i></button><button value="+value.id+" OnClick='Mostrar(this); ' class='btn btn-primary' data-toggle='modal' data-target='#editar-modal' ><i class='fa fa-pencil-square'></i></button></div></td></tr>");
});
});
}
Error :
QueryException in Connection.php line 636:SQLSTATE[42S22]: Column not found: 1054 Unknown column 'asc' in 'order clause' (SQL: select * from `Citas` order by `asc` asc limit 10 offset 0)