Laravel Route for Search - laravel

I try this tutorial on laravel about Live Search
But it's on the homepage(index)
I want to access it to localhost/laravel/public/search
Here is the Controller
class SearchController extends Controller
{
public function index()
{
return view('search.search');
}
public function search(Request $request)
{
if ($request->ajax())
$output ="";
$orderinfo=DB::table('tb_order')->where('shipcustomername','LIKE','%' . $request->search.'%' )
->orWhere('orderId','LIKE','%' .$request->search. '%')->get();
if ($orderinfo)
{
foreach ($orderinfo as $key =>$orderinfo ){
$output.='<tr>' .
'<td>' .$orderinfo->orderId .'</td>' .
'<td>' .$orderinfo->email .'</td>' .
'<td>' .$orderinfo->subsource .'</td>' .
'</tr>';
}
return Response($output);
}
and my route
Route::get('/' ,'SearchController#index');
Route::get('/search' ,'SearchController#search');
on my resources folder
i have folder search and it's contain the search.blade.php
<div class="container">
<div class="row">
<div class="panel panel-default">
<div class="panel-heading">
<h3>Order Info</h3>
</div>
<div class="panel-body">
<div class="form-group">
<input type="text" class="form-control" id="search" name="search"></input>
</div>
<table class="table table-bordered table-hover ">
<thead>
<tr>
<th>OrderID</th>
<th>Email</th>
<th>SubSource</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
<script type="text/javascript">
$('#search').on('keyup',function(){
$value=$(this).val();
$.ajax({
type : 'get',
url : '{{URL::to('search')}}',
data : {'search':$value},
success:function(data){
$('tbody').html(data);
}
});
});
</script>
</body>
I know this is the route for index ,
Route::get('/' ,'SearchController#index');
But if try to change this to
Route::get('search' ,'SearchController#index');
I get error 500
What is the correct way to route this so it will not use the index
Thank you

There is a good chance that you are sending empty data try to change this:
$value=$(this).val();
to this:
var value = $('#search').val();
If no that then also you are not submitting the data as well add the form:
{{ Form::open(array('method'=>'GET','class'=> 'col-md-6','url' => '/search', 'id'=>'searchform')) }}
<div class="form-group">
<input type="text" class="form-control" id="search" name="search"></input>
</div>
{{ Form::close() }}
change your ajax request to this:
$('#searchform').on('submit', function(e) {
e.preventDefault();
var search = $('#search').val();
$.ajax({
type: "GET",
url: {{URL::to('search')}},
data: {search:search}
success:function(data){
$('tbody').html(data);
}
});
});
If not that then:
set APP_DEBUG in .env to true since the request is ajax, using chrome and press f12, go to Network tab -> click on error -> preview tab, if it just say error with a blank screen, then maybe you should chmod 775(write permissions) and try again

Related

Is there is a way to keep my modal open in Laravel after submit and save the values to db?

I am uploading a file in Laravel 8 with having one bootstrap modal which works dynamically . everything is working fine but I want to improve my output more:
1) Update one of my forms through a modal without refreshing the page?
2) keep the modal open if the validation fails and print the errors to modal instead of my redirect page?
I will appreciate your time helping me.
my form for updating the file
<form action="{{ route('storefile' , $requisition->id) }}" method="POST"
enctype="multipart/form-data">
#csrf
#method('PUT')
<div class="form-group row">
<div class="col-sm-12">
<label for="title"> Account Status: </label>
<select class="form-control" name="acc_status">
<option value="0" {{ $requisition->acc_status == 0 ? 'selected' : '' }}> Inactive
</option>
<option value="1" {{ $requisition->acc_status == 1 ? 'selected' : '' }}> Active
</option>
</select>
</div>
<div class="col-sm-12 pt-4">
<label for="title"> Account document File: </label>
<div>
#if (!empty($requisition->acc_document))
<label class="badge-success">
{{ $requisition->acc_document }}
</label>
#else
<label class="badge-danger">
Nothing uploaded </label>
#endif
</div>
<input type="file" name="acc_document" class="form-control" id="acc_document" />
</div>
</div>
<div class="card-footer">
<div class="row">
<div class="col-md-6 text-left">
<input type="submit" value="Upload document" class="btn btn-primary">
</div>
</div>
</div>
</div>
</form>
my controller and route
public function uploadFile($id) {
$requisition = Requisition::find($id);
return view('requisition.createFile' , compact('requisition'));
}
public function storeFile(Request $request , $id) {
$request->validate([
'acc_status' => 'required',
'acc_document' => 'required|mimes:doc,docx,pdf,txt,zip|max:2000',
]);
$requisition = Requisition::find($id);
$requisition->acc_status = $request->get('acc_status');
$FileName = uniqid() .$request->file('acc_document')->getClientOriginalName();
$path = $request->file('acc_document')->storeAs('uploads', $FileName , 'public');
$requisition->acc_document = '/storage/' . $path;
}
$requisition->save();
//$requisition->update($request->all());
return back()
->with('success', 'Your file has been uploaded successfully.');
}
Route::get('upload/{id}', [RequisitionController::class, 'uploadFile'])->name('upload');
Route::put('requisition/{id}/files', [RequisitionController::class, 'storeFile'])->name('storefile');
and last part my modal and ajax in my index page to upload the file and popup will open
<div class="col-md-6">
<a style="display:inline-block; text-decoration:none; margin-right:10px;"
class="text-secondary" data-toggle="modal" id="mediumButton"
data-target="#mediumModal" title="upload"
data-attr="{{ route('upload' , $requisition->id) }}">
<i class="fas fa-upload"></i>
</a>
</div>
<script>
// display a modal (medium modal)
$(document).on('click', '#mediumButton', function(event) {
event.preventDefault();
let href = $(this).attr('data-attr');
$.ajax({
url: href,
beforeSend: function() {
$('#loader').show();
},
// return the result
success: function(result) {
// #if (count($errors) > 0) #endif
$('#mediumModal').modal("show");
$('#mediumBody').html(result).show();
$("#date-picker").datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'yy-mm-dd'
});
} ,
complete: function() {
$('#loader').hide();
},
error: function(jqXHR, testStatus, error) {
console.log(error);
alert("Page " + href + " cannot open. Error:" + error);
$('#loader').hide();
},
timeout: 8000
});
});
</script>
<!-- medium modal -->
<div class="modal fade" id="mediumModal" tabindex="-1" role="dialog" aria-labelledby="mediumModalLabel"
aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-lg" role="document">
<div class="modal-content">
<div class="modal-body" id="mediumBody">
<form id="modal-form" method="get">
<div>
<!-- the result of displayed apply here -->
</div>
</form>
</div>
</div>
</div>
</div>
#endsection
what I want to implement looks like enter image description here
There are several ways to do this kind of thing. One way to do it, is to do something like this:
Html:
<div class="modal" id="the-modal">
<form action="{{ $theAction }}" method="POST" id="the-form">
<input type="text" name="input-name" id="the-input">
<button type="submit">
</form>
<p id="the-text"></p>
</div>
In your Controller you will return an error or an 200 response, if everything is ok.
public function theAction(Request $request , $id) {
//Do stuff
if (!$error) {
return response("OK"); //This will return a 200 response
} else {
return response("An error happened", 500); //This will return a 500 error
}
}
Then, in your JS, you'll intercept form submission and then, you're going to be able to separate errors from ok messages:
<script>
$("#the-form").on('submit', function(event) {
event.preventDefault();
let theInput = $("#the-input");
$.ajax({
url: theUrl,
data: {
the-input: theInput
}
// 200 response
success: function(result) {
$("#the-text").empty();
$("#the-text").append(result.repsonse);
} ,
error: function(jqXHR, testStatus, error) {
$("#the-text").empty();
$("#the-text").append(error.response);
}
});
});
</script>
If you want to do all this stuff inside a modal, the concept is just the same: You intercept form submission, send to controller, return separate responses for errors and 200 responses, and then update manually the inputs/texts.
I did't test the code, but the concept should work.

insert multiple laravel checkbox datatable

I want to insert multi rows checked in my data table, when I click a button valider, everyone I have a problem in a laravel framework, I want to insert line check in a data table when click on button validate, this my code
the display of the salary list
<body>
<div class="container" id="app">
<div class="list-group">
<div class="list-group-item">
<h3>Pointage Mensuel</h3>
<div class="col-md-6 col-md-offset-3">
<h3>jour : {{$data['datek']}} chantier : {{$data['chantier_name']}}</h3>
</div>
<button class="btn btn-success add-all" data-url="">Valider Pointage de mois</button>
</div>
</div>
<div class="list-group">
<div class="list-group-item">
<table class="table table-bordered">
<tr>
<th>Archive</th>
<th><input type="checkbox" id="check_all"></th>
<th>S.No.</th>
<th>matricule</th>
<th>nom & prenom</th>
<th>salaire net</th>
<th>nbre de jour </th>
<th>prime</th>
</tr>
#if($salaries->count())
#foreach($salaries as $key => $salarie)
<tr id="tr_{{$salarie->id}}">
<td>archive</td>
<td><input type="checkbox" class="checkbox" data-id="{{$salarie->id}}"></td>
<td>{{ ++$key }}</td>
<td>{{ $salarie->matricule }}</td>
<td>{{ $salarie->nom }} {{ $salarie->prenom }}</td>
<td>{{ $salarie->salairenet }}</td>
<td><input type="text" name="nbreJ" class="form-control" value="{{$data['nbr']}}"></td>
<td><input type="text" name="prime" class="form-control" value="0"></td>
</tr>
#endforeach
#endif
</table>
</div>
</div>
<!-------------------//////////////////////////------------->
</div>
</body>
code ajax for checked all /uncheck and
<script type="text/javascript">
$(document).ready(function () {
$('#check_all').on('click', function(e) {
if($(this).is(':checked',true)) {
$(".checkbox").prop('checked', true);
} else {
$(".checkbox").prop('checked',false); } });
$('.checkbox').on('click',function(){
if($('.checkbox:checked').length == $('.checkbox').length){
$('#check_all').prop('checked',true);
}else{
$('#check_all').prop('checked',false); }});
$('.add-all').on('click', function(e) {
var idsArr = [];
$(".checkbox:checked").each(function() {
idsArr.push($(this).attr('data-id'));});
if(idsArr.length <=0) {
alert("Please select atleast one record to pointer.");
} else {
var strIds = idsArr.join(",");
$.ajax({
url: "{{ route('salarie.multiple-add') }}",
type: 'POST',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: {
'ids' : strIds},
success: function (data) {
if (data['status']==true) {
$(".checkbox:checked").each(function() {
alert(strIds); });
alert(data['message']);
} else {
alert('Whoops Something went wrong!!');}
window.location.reload()},
error: function (data) {
alert(data.responseText);}});} }); });
</script>
function controller addMultiple
public function addMultiple(Request $request){
$pointage=new Pointage();
$pointage->datep=$request->datep;
$pointage->nbrj=$request->nbrj;
$pointage->prime=$request->prime;
$pointage->solde=$request->solde;
return response()->json(['status'=>true]);
}
Apologies for late answer laptop died on me while i was busy but one way you could do it is by using array names for example:
<td><input type="checkbox" class="checkbox" name="row[$key][salarie]" data-id="{{$salarie->id}}"></td>
baiclly if you have multiple of these inputs with the same group it will make an array of inputs on your backend which you can loop through. to test this dd(request()); in your controller function above everything else. then you should be able to see what it returns in your console.
foreach(request(inputgroup) as $value){
Pointage::create([
'some_column' => $value['actualInputName']
]);
}
Update your function to something like this:
public function addMultiple(Request $request){
dd(request());
$pointage=new Pointage();
foreach(request('row') as $row){
// this is the important line $row is your request and ['salari'] is the name of the input
$pointage->salarie = $row['salarie'];
$pointage->save();
}
return response()->json(['status'=>true]);
}

Live Search using Ajax and Getting Error "500 (Internal Server Error)" on Laravel 5.8

I was following tutorial to Live Search using ajax on Laravel, but in the implementation I get error:
GET http://localhost:8000/search?search=k 500 (Internal Server Error)
I was following this tutorial 3 times but always getthis same error. I modified like this:
<!DOCTYPE html>
<html>
<head>
<meta name="_token" content="{{ csrf_token() }}">
<title>Live Search</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="panel panel-default">
<div class="panel-heading">
<h3>Products info </h3>
</div>
<div class="panel-body">
<div class="form-group">
<input type="text" class="form-controller" id="search" name="search">
<input type="hidden" name="_method" value="POST">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</div>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>ID</th>
<th>Product Name</th>
<th>Description</th>
<th>Price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$('#search').on('keyup',function() {
$value=$(this).val();
$.ajax({
type : 'get',
url : '{{URL::to('search')}}',
data:{'search':$value},
success:function(data){
$('tbody').html(data);
}
});
});
</script>
<script type="text/javascript">
$.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });
</script>
</body>
</html>
my controller:
public function search(Request $request)
{
if($request->ajax()) {
$output="";
$products=DB::table('products')->where('title','LIKE','%'.$request->search."%")->get();
if($products) {
foreach ($products as $key => $product) {
$output.='<tr>'.
'<td>'.$product->id.'</td>'.
'<td>'.$product->title.'</td>'.
'<td>'.$product->description.'</td>'.
'<td>'.$product->price.'</td>'.
'</tr>';
}
return Response($output);
}
}
}
I was trying this code for 3 different database and always get the same error 500 .
You have call ajax using get method, so first check your route file.
I think you are calling search method using post method.
Also in ajax code default is get method
you have to specify : method : post
you need to declare variable in Jquery/Javascript like below :
var value=$(this).val();
and pass this variable like below in ajax :
data:{'search':value}
Change above lines ,it should work !

Why the query from controller not display in table using ajax in Laravel?

I want to create a searching filters and display the output using ajax.
This is the button for submit the data:
{!! Form::open(['method' => 'POST', 'action' => 'Modul\CarianAnugerahController#search']) !!}
//Form for filter here...
{{ Form::submit('Cari', ['class' => 'btn btn-primary', 'id' =>'search']) }}
{!! Form::close() !!}
This is the output table under the form:
<div class="panel panel-default">
<div class="panel-heading">Senarai Calon Anugerah</div>
<div class="panel-body">
#if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
#if(Auth::check())
<div class="container table-responsive col-lg-12">
<!-- <div class="container text-center"> -->
<table class="table table-striped table-bordered" id="calon_table" >
<thead>
<tr>
<td class="text-center col-lg-3"><strong>Name</strong></td>
<td class="text-center"><strong>Action</strong></td>
<!-- <td class="text-center"><strong>Lihat Rekod</strong></td> -->
</tr>
</thead>
<tbody id="calon_anugerah">
</tbody>
</table>
<!-- </div> -->
</div>
#endif
#if(Auth::guest())
Anda perlu log masuk.
#endif
</div>
</div>
</div>
The ajax code to get the data is:
<script type="text/javascript">
$('#search').on('click', function(){
$.get("{{ URL::to('search-calon') }}",function(data){
$.each(data, function(i, value){
var tr =$("<tr/>");
tr.append($("<td/>",{
text : value.name
}))
$('#calon_anugerah').append(tr);
});
})
})
</script>
I had queried the data using the code in CarianAnugerahController#search:
$query = DB::table('itemregistrations')
->select('itemregistrations.ItemRegistrationID','itemregistrations.name', 'itemregistrations.Nobadan');
if(request('umur')) {
$query->whereRaw('YEAR(CURDATE()) - lahir_yy >= ?', [request('umur')]);
}
if(request('negeri_lahir')) {
$query->where('NegeriID', request('negeri_lahir'));
}
if(request('kategori')) {
$query->where('CategoryID', request('kategori'));
}
if(request('pangkat')) {
$query->where('OperasiID', request('pangkat'));
}
$newitem = $query->get();
return response($newitem);
This is the route:
Route::resource('carian_anugerah', 'Modul\CarianAnugerahController');
Route::post('/search-calon', 'Modul\CarianAnugerahController#search');
I can get the value but it doesn't display in table..it shows the output in json format in a white page..
example output..in browser.
What is missing in the ajax code?
I guess you should remove form action and method. Because if you are submitting form via ajax you dont need action and method. Due to action and method your form is submitting like normal post of form data and that`s why you are receiving output on browser.
{!! Form::open() !!}
{{ csrf_field() }}
//Form for filter here...
{{ Form::submit('Cari', ['class' => 'btn btn-primary', 'id' =>'search']) }}
{!! Form::close() !!}
Try these changes and see if you are getting desired result. And make ajax call with post, your search-calon route is POST
<script type="text/javascript">
$('#search').on('click', function(){
$.post("{{ URL::to('search-calon') }}",function(data){
$.each(data, function(i, value){
var tr =$("<tr/>");
tr.append($("<td/>",{
text : value.name
}))
$('#calon_anugerah').append(tr);
});
})
})
</script>

Why ajax calling for search doesn't display output?

I had search field using ajax call in laravel 5. It search in Db and display output in table. When user click on the page, it should display all db query. When user type in search field it should display the output according to the search input.
This is the controller for searching:
function action(Request $request)
{
if($request->ajax())
{
$output = '';
$query = $request->get('query');
if($query != '')
{
$data = DB::table('itemregistrations')
->where('name', 'like', '%'.$query.'%')
->paginate(10);
}
else
{
$data = DB::table('itemregistrations')
->paginate(10);
}
$total_row = $data->count();
if($total_row > 0)
{
foreach($data as $row)
{
$output .= '
<tr>
<td>'.$row->name.'</td>
<td>'.$row->seksyen_kecil.'</td>
<td>'.$row->nobadan.'</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);
}
}
This is the view blade displaying the output:
<div class="row">
<div class="form-group">
<div class="col-lg-5">
<input type="text" class="form-control" id="search" name="search"></input>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">Senarai Kakitangan</div>
<div class="panel-body">
#if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
#if(Auth::check())
<div class="container table-responsive col-lg-12">
<!-- <div class="container text-center"> -->
<h3 align="center">Total Data : <span id="total_records"></span></h3>
<table class="table table-striped table-bordered">
<thead>
<tr>
<td><strong>#</strong></td>
<td class="text-center col-lg-1"><strong>Nama</strong></td>
<td class="text-center col-lg-3"><strong>Seksyen</strong></td>
<td class="text-center col-lg3-2"><strong>No Badan</strong></td>
</tr>
</thead>
<tbody>
</tbody>
</table>
<!-- </div> -->
<ul class="pagination pull-right">
{{ $itemregistrations->links() }}
</ul>
</div>
#endif
#if(Auth::guest())
Anda perlu log masuk.
#endif
</div>
</div>
</div>
The javascript for searching:
<script>
$(document).ready(function(){
fetch_profil_data();
function fetch_profil_data(query = '')
{
$.ajax({
url:"{{ route('live_search.action') }}",
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_profil_data(query);
});
});
</script>
The route for the search is:
Route::get('/profil/action', 'Modul\ProfilController#action')->name('live_search.action');
I couldn't find any error and console.log also doesn't produce any output..
The searching doesn't work and don't display any result.
The script link i put in app.blade.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
This is the error in log
C:\\xampp\\htdocs\\hre1m\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Http\\Kernel.php(116): Illuminate\\Foundation\\Http\\Kernel->sendRequestThroughRouter(Object(Illuminate\\Http\\Request))
#50 C:\\xampp\\htdocs\\hre1m\\public\\index.php(53):
Illuminate\\Foundation\\Http\\Kernel->handle(Object(Illuminate\\Http\\Request))
#51 C:\\xampp\\htdocs\\hre1m\\server.php(21):
require_once('C:\\\\xampp\\\\htdocs...')
#52 {main}
"}

Resources