I am trying to search users in a panel with ajax. But along with that, I also want to edit the selected user.
I have created the button inside the controller to achieve this but the button isn't working.
Here is my controller code:
public function searchTeacher(Request $request){
if($request->ajax()){
$output = '';
$query = $request->get('query');
if($query != '')
{
$data = DB::table('users')->where('name', $query)->get();
}else{
$data = DB::table('users')->get();
}
$total_row = $data->count();
if($total_row > 0)
{
foreach($data as $row)
{
$output .= '
<tr>
<td>'.$row->name.'</td>
<td>'.$row->email.'</td>
<td>'.$row->teacherId.'</td>
<td>'.$row->subject.'</td>
<td> <button href={{route(update-teacher-view), '.$row->id.'}}> Edit</button> </td>
</tr>
';
}
}
else
{
$output = '
<tr>
<td align="center" colspan="5">No Data Found</td>
</tr>
';
}
$data = array(
'table_data' => $output,
'total_data' => $total_row
);
echo json_encode($data);
}
}
Here is the ajax for search method-
<script>
$(document).ready(function(){
fetch_customer_data();
function fetch_customer_data(query = '')
{
console.log(query)
$.ajax({
url:"{{ route('search-teacher') }}",
method:'GET',
data:{query:query},
dataType:'json',
success:function(data)
{
$('tbody').html(data.table_data);
$('#total_records').text(data.total_data);
}
})
}
$(document).on('keyup', '#search', function(){
var query = $(this).val();
fetch_customer_data(query);
});
});
Here is my html-
<section class="panel">
<table class="table table-striped">
<thead class="team-list chat-list-side info border-less-list">
<th>Teacher Name</th>
<th>Email</th>
<th>Teacher Id</th>
<th>Subject</th>
</thead>
<tbody>
</tbody>
</table>
</section>
A solution will be appreciated.
Thanks in advance.
Maybe it's a wrong string interpolation? Should be like this:
<?php
$output .= '
<tr>
<td>'.$row->name.'</td>
<td>'.$row->email.'</td>
<td>'.$row->teacherId.'</td>
<td>'.$row->subject.'</td>
<td> <button href='.route('update-teacher-view', $row->id).'> Edit</button> </td>
</tr>
';
Also instead of echo-ing, just return the value, it will be automatically converted to JSON response:
// echo json_encode($data); // Change this line to below
return $data;
Render the blade file with the data this is the best solution.
In controller
return View::make('ajaxFilter',compact('data'))->render();
On ajaxFilter.blade.php
<section class="panel">
<table class="table table-striped">
<thead class="team-list chat-list-side info border-less-list">
<th>Teacher Name</th>
<th>Email</th>
<th>Teacher Id</th>
<th>Subject</th>
</thead>
<tbody>
#if($data->count() > 0)
#foreach($data as $row)
<tr>
<td>{{ $row->name }}</td>
<td>{{ $row->email }}</td>
<td>{{ $row->teacherId }}</td>
<td>{{ $row->subject }}</td>
<td>
Edit //button design
</td>
</tr>
#endforeach
#else
No data Found
#endif
</tbody>
</table>
</section>
On ajax response, you can append HTML data something like that
$('#div_or_section_id').html(data);
Related
I am new to Laravel and coding and stuck at point where i want to change to data table data (tbody) as per selection box value. The code is as below.
On Page load table shows data as per default selection. After ajax success, alert is showing the correct data
Selection box
<div class="form-inline">
<label><strong>Select Option :</strong></label>
<select id='selectoption' class="form-control" style="width: 150px">
<option value="material">By Material</option>
<option value="supplier">By Supplier</option>
</select>
</div>
Table
<table id="expensestable" class="table table-bordered table-hover" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>Material / Supplier</th>
<th>From Date</th>
<th>To Date</th>
<th>Total Quantity</th>
<th>Total Amount</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach ($expdatabymaterial as $i )
<tr>
<td>{{$i->materialid}}</td>
<td>{{$i->material}}</td>
<td>{{ date('d-m-Y', strtotime ($startdateofmonth)) }}</td>
<td>{{ date('d-m-Y', strtotime ($enddateofmonth)) }}</td>
<td>{{$i->totalquantity}}</td>
<td>{{$i->totalamount}}</td>
<td>
<button type="button" class="deletedatabtn btn btn-primary"><i class="far fa-eye" title="View"></i></button>
</td>
</tr>
#endforeach
</tbody>
</table>
Ajax
$('#selectoption').change( function() {
var selectoption = $(this).find('option:selected').val();
var token = "{{ csrf_token() }}";
$.ajax({
type: 'post', //'POST'
url: '/changeselection',
data: { option: selectoption, _token: token, },
success: function (data) {
alert(data)
}
});
});
Controller
$startdateofmonth = new Carbon('first day of this month');
$enddateofmonth = new Carbon('last day of this month');
if ($req->get('option') == 'material')
{
$expdatabymaterial = Dairyexpense::selectraw('material, material, materialid, materialid, SUM(quantity) as "totalquantity", SUM(totalamount) as "totalamount"')
->whereBetween('expensesdate', [$startdateofmonth, $enddateofmonth])
->groupBy('material','materialid')->get();
return response([$expdatabymaterial]);
}
else
{
$expdatabysuuplier = Dairyexpense::selectraw('supplier, supplier, supplierid, supplierid, SUM(quantity) as "totalquantity", SUM(totalamount) as "totalamount"')
->whereBetween('expensesdate', [$startdateofmonth, $enddateofmonth])
->groupBy('supplier','supplierid')->get();
return response([$expdatabysuuplier]);
}
Thanks in advance for support and help.....
I want to add action button to my datatable here the code
html table and datatables
<table id="users-table" class="table table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>alamat</th>
<th>nohp</th>
<th>action</th>
</tr>
</thead>
</table>
<script id="script">
$(function () {
$('#users-table').DataTable({
processing: true,
serverSide: true,
ajax: 'test/json'
});
});
</script>
heres the laravel json datatables
public function data(Datatables $datatables)
{
$builder = Kontak::query()->select('id', 'nama', 'email', 'alamat', 'nohp');
return $datatables->eloquent($builder)
->addColumn('action', 'users.datatables.intro')
->rawColumns(['action'])
->make();
}
but it keeps show result like this
result images
You should try ->escapeColumns([]) before ->addColumn('action', 'users.datatables.intro')
You can use the routes methods for your model.
view :
<div class="table-responsive">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>alamat</th>
<th>nohp</th>
<th>action</th>
</tr>
</thead>
<tbody>
#foreach($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->alamat }}</td>
<td>{{ $user->nohp }}</td>
<td>
<form action="{{ route('users.destroy' , ['id' => $user->id]) }}" method="post">
{{ method_field('delete') }}
{{ csrf_field() }}
<div class="btn-group btn-group-xs">
edit
<button type="submit" id="deleteButton" data-name="{{ $user->id }}" class="btn btn-xs btn-warning">delete</button>
</div>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
controller:
public function index()
{
$users = User::latest()->paginate(25);
return view('users.all' , compact('users'));
}
change users.all to your users view.
In laravel, I am using search bar in list view, It will search from the record using ajax and display me the output.
But it's now working, when i write any text in search bar I didn't get any output. All records displays as it is.
My database in mongoDb, and i am coding in laravel.
Here is my view file code.
view
<div class="table-responsive m-t-40">
<div class="form-group">
<input type="text" name="search" id="search" class="form-control" placeholder="Search Department" />
</div>
<table class="table table-bordered table-striped ">
<thead>
<tr>
<th>Department Name</th>
<th>Created By</th>
<th>Created On</th>
#if (App\User::isPermitted(['edit_department', 'update_department', 'delete_department']))
<th>Action</th>
#endif
</tr>
</thead>
<tbody>
#if($listOfDepartment != null)
#foreach($listOfDepartment as $departmentList)
<tr>
<td>{{$departmentList->nameOfDepartment}}</td>
<td>{{$departmentList->createdBy}}</td>
<td>{{$departmentList->created_at}}</td>
#if (App\User::isPermitted(['edit_department', 'update_department', 'delete_department']))
<td>
<i class="fa fa-edit fa-lg" style="color:#0066ff" aria-hidden="true"></i>
<i class="fa fa-trash fa-lg" onclick="delete_user(this); return false;" style="color:red" aria-hidden="true"></i>
</td>
#endif
</tr>
#endforeach
#endif
</tbody>
</table>
</div>
script
<script>
$(document).ready(function(){
fetch_customer_data();
function fetch_customer_data(query = '')
{
$.ajax({
url:"{{ route('list_department') }}",
method:'GET',
data:{query:query},
dataType:'json',
success:function(data)
{
$('tbody').html(data.table_data);
}
})
}
$(document).on('keyup', '#search', function(){
var query = $(this).val();
fetch_customer_data(query);
});
});
</script>
and here is my code of controller file
namespace App\Http\Controllers;
use App\Department;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
public function listDepartment(Request $request)
{
$listOfDepartment = Department::all();
if($request->ajax())
{
$output = '';
$query = $request->get('query');
if($query != '')
{
$data = Schema::table('department')
->where('nameOfDepartment', 'like', '%'.$query.'%')
->orWhere('createdBy', 'like', '%'.$query.'%')
->get();
}
else
{
$data = Schema::table('department')
->orderBy('nameOfDepartment', 'asc')
->get();
}
$total_row = $data->count();
if($total_row > 0)
{
foreach($data as $row)
{
$output .= '<tr>
<td>'.$row->nameOfDepartment.'</td>
<td>'.$row->createdBy.'</td>
</tr>';
}
}
else
{
$output = '
<tr>
<td align="center" colspan="5">No Data Found</td>
</tr>
';
}
$data = array(
'table_data' => $output,
'total_data' => $total_row
);
echo json_encode($data);
}
return view('pages.department', compact('listOfDepartment'));
}
I want to create a word file as a report. I want to fetch all data from the table and put to the word file but I am not able to save data to the file. I am doing in laravel 5.2. File is getting created and downloaded but data which is coming from database is not getting saved. thanks everyone
Here is my controller code -
public function downloadAbleFile(Request $request){
//Fetching all records based on projectid
$project_id = $request->input('project_id');
$questiondetails = DB::table('questionnair')->where('project_id','=',$project_id)->get();
$headers = array(
"Content-type"=>"text/html",
"Content-Disposition"=>"attachment;Filename=report.doc"
);
$content = '<html>
<head>
<meta charset="utf-8">
</head>
<body>
<p>
<table>
<thead>
<tr>
<th>Project ID</th>
<th>Question Number</th>
<th>User ID</th>
<th>Answer</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
function project(){
foreach ($questiondetails as $question){
return(
echo "<tr>";
echo "<td>".$question->project_id."</td>";
echo "<td>".$question->question_num."</td>";
echo "<td>".$question->user_id."</td>";
echo "<td>".$question->answer."</td>";
echo "<td>".$question->status."</td>";
echo "</tr>";
);
}
}
project();
?>
</tbody>
</table>
</p>
</body>
</html>';
return Response::make($content,200, $headers);
}
Why do not you use blade?
Try this
in your controller:
public function downloadAbleFile(Request $request){
$project_id = $request->input('project_id');
$questiondetails = DB::table('questionnair')->where('project_id','=',$project_id)->get();
$headers = array(
"Content-type" => "text/html",
"Content-Disposition" => "attachment;Filename=report.doc"
);
$content = View::make('path.view', [
'questiondetails' => $questiondetails,
])->render();
return Response::make($content,200, $headers);
}
in your view
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<br>
<table>
<thead>
<tr>
<th>Project ID</th>
<th>Question Number</th>
<th>User ID</th>
<th>Answer</th>
<th>Status</th>
</tr>
</thead>
<tbody>
#foreach($questiondetails as $question)
<tr>
<td>{{ $question->project_id }}</td>
<td>{{ $question->question_num }}</td>
<td>{{ $question->user_id }}</td>
<td>{{ $question->answer }}</td>
<td>{{ $question->status }}</td>
</tr>
#endforeach
</tbody>
</table>
<br>
</body>
</html>
I have data in the view like so
<div class="box-body table-responsive no-padding">
<div id="users-table-wrapper">
<table id="users_table" class="table table-hover table-striped">
<tbody>
<tr>
<th>#lang('app.soldto')</th>
<th>#lang('app.soldby')</th>
<th>#lang('app.network')</th>
<th>#lang('app.plan')</th>
<th>#lang('app.sales_date')</th>
</tr>
#if (count($sales))
#foreach ($sales as $sale)
<tr>
<td>{{ $sale->soldto ?: trans('app.n_a') }}</td>
<td>{{ $sale->first_name . ' ' . $sale->last_name }}</td>
<td>{{ $sale->name }}</td>
<td>{{ $sale->plan }}</td>
<td>{{ $sale->salesdate }}</td>
</tr>
#endforeach
#else
<tr>
<td colspan="6"><em>#lang('app.no_records_found')</em></td>
</tr>
#endif
</tbody>
</table>
{!! $sales->render() !!}
</div>
</div>
</div>
I use pagination to display 10 rows per page. Like below
I want to download all this data to CSV. Without running the db query again.
Datatable itself provide the buttons to export csv, xls ,pdf etc. Here is the code
$('#example').DataTable( {
dom: 'Bfrtlp',
buttons: ['csv','pdf']
} );
'#example' is the id of your table
You can use working code below:
public static function exportCsv()
{
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$rows = DB::select( DB::raw("select * from users
;") );
$rows = json_decode(json_encode((array) $rows), true);
//\Log::info('query'.print_r($rows,true));
ob_end_clean();
$out = fopen('php://output', 'w');
foreach($rows as $key=>$values)
{
$arr = [];
foreach ($values as $key=>$value) {
array_push($arr, $key);
}
$line = $arr;
fputcsv($out, $line);
break;
}
//fputcsv($out, array('Registration', 'Name', 'Checkin Time'));
foreach($rows as $lines)
{
$line = $lines;
fputcsv($out, $line);
}
die;
fclose($out);
}