How can page through the results? laravel - php

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)

Related

Error when trying to put Action Button (using Json method)

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;
);
}

How to pass route with {id} to Datatable blade. To view specific user details

This is my route
Route::get('/view/{id}', [
'uses' => 'ClientController#view',
'as' => 'view'
]);
This is my Client controller
public function view($id){
$client = Client::where('id',$id)->first();
return view('view',compact('client'));
}
This is my datatable
#extends('layouts.datatables_master')
#section('content')
<table class="table table-bordered" id="clients-table">
<thead>
<tr>
<th>ID</th>
<th>Company Name</th>
<th>Name</th>
<th>Surname</th>
<th>ID Number</th>
<th>Created</th>
<th>Last Updated</th>
<th>Actions</th>
</tr>
</thead>
</table>
#stop
#push('scripts')
<script>
$(function() {
$('#clients-table').DataTable({
processing: true,
serverSide: true,
ajax: '{!! route('business.list') !!}',
columns: [
{ data: 'id', name: 'id' },
{ data: 'companyname', name: 'companyname' },
{ data: 'name', name: 'name' },
{ data: 'surname', name: 'surname' },
{ data: 'idnumber', name: 'idnumber' },
{ data: 'created_at', name: 'created_at' },
{ data: 'updated_at', name: 'updated_at' },
{ data: "actions",
"render": function(data, type, row) {
return '<i class="fa fa-search" title="View"></i> <i class="fa fa-pencil" data-toggle="tooltip" data-placement="top" title="Edit"></i> <i class="fa fa-trash" data-toggle="tooltip" data-placement="top" title="Delete"></i>'
;}
}
]
});
});
</script>
#endpush
Problem
My Main issue is passing an ID for all users. If you check my render function on my DataTable I said return route(view,1) where it's 1. I want to pass $id but it says undefined variable. Please help.
You could return the generated route link from your controller like:
return datatables(Client::query())
->addColumn('actions', function ($client) {
return [
'edit_link' => route('view', [$id => $client->id]),
];
})->toJson();
and render in your view as
{
data: "actions",
render: function(data, type, row) {
return
'<a href="' + data.edit_link + '" class="btn btn-xs btn-info">' +
'<i class="fa fa-search" title="View"></i></a>' +
'<a href="#" class="btn btn-xs btn-primary">' +
'<i class="fa fa-pencil" data-toggle="tooltip" data-placement="top" title="Edit"></i>' +
'</a>' +
'<a href="#" class="btn btn-xs btn-danger">' +
'<i class="fa fa-trash" data-toggle="tooltip" data-placement="top" title="Delete"></i>' +
'</a>';
}
}
the value of data should be an 'id', and use url() instead of route() :
{ data: "id",
"render": function(data, type, row) {
return '<a href="{{ url("view") }}/"'+ data +'>View</a>';
}
}
Try like this
return '<i class="fa fa-search" title="View"></i>
You pass the client variable to blade
{{ route('view',$client->id); }}

Where clause in mysql not working

I am working on a project using php codeigniter,i am using mysql select query to fetch all data from database where isactive field is equal to 1.but i am unable to do it.below is the function where i have writtten the query.
Code:
public function displayinfo3()
{
$user_id = $this->session->userdata('user_id');
if($user_id)
{
$this->load->library('datatables');
$this->datatables
->select("user_type.user_type as user_type,user.user_name as user_name,user.first_name as first_name,user.middle_name as middle_name,user.last_name as last_name,user.user_id as Actions")
->from("user")
->where('isactive'==1)
->join("user_type","user_type.user_type_id=user.user_type_id","left")
->edit_column("Actions",
"<center><div class='visible-md visible-lg hidden-sm hidden-xs'><div align='center'><div class='col-md-2'><form action='".base_url()."index.php/Registrationc/editpatient3' method='post'><input type='hidden' id='editp3' name='editp3' value='$1'><button title='EDIT PATIENT' class='tip btn btn-primary btn-xs' type='submit' value='Submit' ><i class='fa fa-edit'></i></button></form></div><div class='col-md-2'><a class=\"tip btn btn-danger btn-xs\" title='DELETE PATIENT' href='#' onclick=\"delete_patient('$1')\" ><i class=\"fa fa-trash-o\"></i></a></div></div></div></center>", "Actions");
// $this->datatables->unset_column('Sno.patient_id');<form action=""><div class='btn-group'>
//<a class=\"tip btn btn-primary btn-xs\" onclick=\"edit_patient('$1')\" title='EDIT MAPPING' href='#' return false;\"><i class=\"fa fa-edit\"></i></a>
echo $this->datatables->generate();
}
else
{
redirect(base_url('Registrationc/extra1'));
}
}
Replace ->where('isactive'==1) with ->where('isactive = 1')
The first passes the result of the comparison of 'isactive' with 1 to the function. As 'isactive' is not equal to 1 you just pass a false value to your where statement.
The second call passes the correct query string to be put in the where statement of the query.
You need to change the ->where('isactive'==1) to ->where('isactive = 1') and returns a bool result.

Laravel and yajrabox Datatables server side proccessing

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);
}

CodeIgniter ajax post only working once

Hello I'm trying to delete a row in the database using ajax post but the problem is that the row gets deleted only once per page load. The row get detach from the HTML DOM everything I press the delete button, but the database only deletes one record. I want to delete therecord in the database every time I press the delete button. How can I achieve this ?
My view
<tbody id="tbody"><?php
$count = 1;
foreach($rows as $row):?>
<tr>
<td><?=$count?></td>
<td><a href="basic_table.html#">
<?=$row->FirstName." ".$row->LastName?></a>
</td>
<td class="hidden-phone"><?=$row->Email?></td>
<td><?=$row->Password?></td>
<td><span class="label label-warning label-mini">
<?=date("m/d/Y", strtotime($row->Created))?></span>
</td>
<td>
<button class="btn btn-success btn-xs">
<i class="fa fa-check"></i></button>
<button class="btn btn-primary btn-xs">
<i class="fa fa-pencil"></i>
</button>
<button id="delete" data-id="<?=$row->id?>"
data-url="<?=base_url()?>" class="btn btn-danger
btn-xs"><i class="fa fa-trash-o "></i>
</button>
</td>
</tr><?php
$count++;
endforeach?>
</tbody>
script
$(document).ready(function()
{
$("#tbody").on('click','#delete', function()
{
var id = $("#delete").data("id");
var url = $("#delete").data("url");
$.post(url + "users/delete", { id : id, cache: false } , function()
{
},"json");
$(this).closest('tr').detach();
});
});
Please give the codeigniter controller script
You must change to anchor tag and add preventDefault() to prevent reloading page
$(document).ready(function(){
$("#tbody").on('click','#delete', function(e){
//You must add e.preventDefault() to avoid reloading page
e.preventDefault();
var id = $("#delete").data("id");
var url = $("#delete").data("url");
$.post(url + "users/delete", { id : id, cache: false } , function(){
},"json");
$(this).closest('tr').detach();
});
});

Categories