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

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>

Related

How to get my link to display as a link from my laravel controller

I'm trying to send an error message with a link. The issue I'm having is that when I get the error I get the html version of my link
EG: Please go to product
What I would like is for my error message to say Please go to product where as product would be a link.
Here is my code
public function updateProduct(Product $product)
{
if(!empty($product->status))
{
$url = "Product";
return redirect()->route('product.index', [$product])->with('error', "Go to $url.");
}
}
and in my index.blade.php
I have this
#section('content')
<div class="row justify-content-center">
<div class="col-md-12">
<div class="card">
<div class="card-body">
<table class="table">
#foreach($products as $product)
<tr>
<td>
{{ $product->name }}
</td>
</tr>
#endforeach
</table>
</div>
</div>
</div>
</div>
#endsection
#push('js')
<script type="text/javascript">
#if(session('error'))
Swal.fire('Error!', '{{ session('error') }}', 'error');
#endif
</script>
#endpush
you are sending html as response. you have to use {!! !!} to print that response as your expectation.
#push('js')
<script type="text/javascript">
#if (session('error'))
Swal.fire('Error!', '{!! session('error') !!}', 'error');
#endif
</script>
#endpush
this will show the swal as Go to Product

Why output using ajax not display in table but json format?

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){
// alert(value.name);
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?

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}
"}

Laravel Route for Search

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

how to clear cache search results from server in laravel 5?

i'm new to laravel and i've created a simple search to query my database.
the problem is that everytime i refresh the page all the results from my last search are still showing. also when i load the page after couple of days,results are the. it seems like there is a cache working which i dont know about.
i want to clear these results/cache without clearing the cache for all my app.
Here is the code.
in my routs file:
Route::get('men',function()
{
$query=Request::get('q');
if ($query)
{
$users= \App\User::where('first_name','LIKE',"%$query%")
->orwhere('last_name','LIKE',"%$query%")
->get();
}
else
{
}
return view('page')->withUsers($users);
});
My View:(page.blade.php)
{!! Form::open(['method' => 'GET']) !!}
<div class="container col-lg-6 form-group" style="float:none;margin:auto">
<div class="input-group">
{!! Form::input('search','q', null, ['placeholder' => 'search' ,
'class' => 'form-control', 'autocomplete' => 'off']) !!}
<div class="input-group-btn">
<button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Search</button>
</div><!-- /btn-group -->
</div><!-- /input-group -->
</div>
{!! Form::close() !!}
<div class="container col-lg-6" style="float:none;margin:auto">
#if ($users->count())
<ul class="list-group" style="list-style-type: none;">
#foreach($users as $user)
<li class="list-group-item" style="cursor:pointer">
{{$user->first_name}} {{$user->last_name}}
</li>
#endforeach
</ul>
#else
<h3>Sorry,no users found...</h3>
#endif
</div>
</div> <!--container-->
any Ideas ??..
i've managed to clear last query string in the browser addess bar with:
within my view:
<head>
<script type="text/javascript">
var uri = window.location.toString();
if (uri.indexOf("?") > 0) {
var clean_uri = uri.substring(0, uri.indexOf("?"));
window.history.replaceState({}, document.title, clean_uri);
}
</script>
</head>
whenever i refresh the page it clears up the results since nothing is coming from the server.

Resources