Why ajax calling for search doesn't display output? - ajax

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

Related

Laravel: Ajax live search returns error 405 (METHOD NOT ALLOWED)

I'm following a tutorial to implement live search feature in my laravel project using ajax and this video: https://www.youtube.com/watch?v=Mylh7H844Ro.
I'm following the tutorial and understand every stap he takes but I recieve an error 405 (Method not allowed).
Can anyone see what I'm doing wrong?
Here's my code:
My view:
<body class="relative min-h-screen">
#include('partials.header')
<main class="md:w-3/5 m-auto pb-20 space-y-10">
<div class="p-2 mt-4 flex justify-center items-center">
<p class="w-10/12">Welkom Admin. Op deze pagina kan je al onze gebruikers terugvinden en heb je beheer over hun geboortelijst.
</p>
</div>
<div class="bg-mid p-4 mb-8 flex flex-row justify-between items-center ">
<h3 class=""><strong>Gebruikers</strong></h3>
</div>
<input type="search" name="search" id="search" class="border-2 rounded-lg p-2">
<div class="w-full bg-mid p-2" id="Table">
</div>
</main>
#include('partials.footer')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" integrity="sha512-+NqPlbbtM1QqiK8ZAo4Yrj2c4lNQoGv8P79DPtKzj++l5jnN39rHA/xsqn8zE9l0uSoxaCdrOgFs6yjyfbBxSg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha512-ldc1sPu1FZ8smgkgp+HwnYyVb1eRn2wEmKrDg1JqPEb02+Ei4kNzDIQ0Uwh0AJVLQFjJoWwG+764x70zy5Tv4A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
{{-- Script voor live searching --}}
<script>
$(document).ready(function(){
$('#search').on('keyup', function(){
const query = $(this).val();
$.ajax({
url:"search",
type: "GET",
data:{'search': query},
success: function(data){
$('$Table').html(data);
}
});
});
});
</script>
</body>
My routes:
Route::get('/admin/home', [AdminController::class, 'adminHome'])
->name('adminhome');
Route::get('/admin/home/search', [AdminController::class, 'search'])
->name('search');
My Controller:
public function search(Request $request)
{
$users = User::where('role', '=', 'user')->get();
if($request->ajax()) {
$data = $users->where('id', 'like', '%'.$request->match.'%')
->orwhere('name', 'like', '%'.$request->match. '%')
->orwhere('email', 'like', '%'.$request->match. '%')->get();
$output = '';
if (count($data) > 0) {
$output = `
<table>
<thead>
<tr>
<th scope="col">Id</th>
<th scope="col">Naam</th>
<th scope="col">E-mail</th>
</tr>
</thead>
<tbody>`;
foreach ($data as $row) {
$output .=`
<tr>
<th scope="row">`.$row->id.`</th>
<td>`.$row->name.`</td>
<td>`.$row->email.`</td>
</tr>
`;
}
$output .= `
</tbody>
</table>`;
}
} else {
$output = 'Geen gebruikers voldoen aan uw zoekcriteria..';
}
}
You can try this:
$(document).ready(function(){
let url = "{{ route('search') }}"
$('#search').on('keyup', function(){
const query = $(this).val();
$.ajax({
url: url,
type: "GET",
data:{'search': query},
success: function(data){
$('$Table').html(data);
}
});
});
});

problem in datatable when use in livewire component

i use livewire defer loading for load data after rendering page.
After opening the page, the information is successfully received and displayed in the table
But the problem is that I use datatable and when the received information is displayed, datatable becomes a simple table. As if I did not use datatable at all.
This is the livewire component code
class Cryptolist extends Component
{
public bool $loadData = false;
public function init()
{
$this->loadData = true;
}
public function render()
{
try {
if ($this->loadData) {
$api = new \Binance\API('api','secret');
$prices = $api->coins();
$one = json_encode($prices, true);
$coins = json_decode($one , true);
} else {
$coins = [];
}
return view('livewire.backend.crypto.cryptolist')->with('coins' , $coins);
}catch(\Exception $e)
{
return view('wrong')->with('e' , $e);
}
}
}
And this is the component view where the table is located and displays the received information
<div wire:init="init">
#if ($loadData)
<div id="loadesh1" wire:ignore>
<table class="datatable-init nk-tb-list nk-tb-ulist" data-auto-responsive="false">
<thead>
<tr class="nk-tb-item nk-tb-head">
<th class="nk-tb-col"><span class="sub-text">name</span></th>
<th class="nk-tb-col tb-col-mb"><span class="sub-text">balance</span></th>
</tr>
</thead>
<tbody>
#foreach ($coins as $item => $value)
<tr class="nk-tb-item">
<td class="nk-tb-col">
<div class="user-card">
<div class="user-avatar d-none d-sm-flex">
#if(file_exists(public_path() . '/img/crypto/'.strtolower($value['coin'].".svg")))
<img style="border-radius: 0"
src="{{asset('/img/crypto/'.strtolower($value['coin']))}}.svg" class="img-fluid"
alt="">
#else
<img style="border-radius: 0"
src="https://demo.rayanscript.ir/-/vendor/cryptocurrency-icons/32/color/noimage.png"
class="img-fluid" alt="">
#endif
</div>
<div class="user-info">
<span class="tb-lead english" style="font-weight: bolder">{{$value['name']}}</span>
<span class="english">{{$value['coin']}}</span>
</div>
</div>
</td>
<td class="nk-tb-col tb-col-mb" data-order="{{$value['coin']}}">
<div class="btn-group" aria-label="Basic example">
<button type="button" class="btn btn-sm btn-dim btn-light"
wire:click="getBalance('{{$value['coin']}}')">
<div wire:loading wire:target="getBalance('{{$value['coin']}}')">
<span class="spinner-border spinner-border-sm" role="status"
aria-hidden="true"></span>
</div>
<span class="w-120px" id="coin-{{$value['coin']}}">get balance</span>
</button>
<button type="button" class="btn btn-sm btn-dim btn-primary">add coin</button>
</div>
</td>
</tr><!-- .nk-tb-item -->
#endforeach
</tbody>
</table>
</div>
#else
Loading data...
#endif
</div>
What do you think is the problem, what code is written incorrectly?

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?

Unable to show data from database in Laravel after inserting data into database

I was able to insert data into database in Laravel but when I was trying to show the data in a tabular form I couldn't - it was displaying Route [stock_edit] not defined. (View: C:\wamp\www\pump\core\resources\views\dashboard\stock-show.blade.php)
Like I said in my quetion yesterday, I am new to Laravel and I am yet to understand the environment. I have been on this for the past 48 hours searching for help online but couldn't find a satisfactory ones
Here is my stock-show.blade.php
#extends('layouts.dashboard')
#section('title', 'All Stock')
#section('content')
#if(count($stock))
<div class="row">
<div class="col-md-12">
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption font-dark">
</div>
<div class="tools"> </div>
</div>
<div class="portlet-body">
<table class="table table-striped table-bordered table-hover" id="sample_1">
<thead>
<tr>
<th>ID#</th>
<th>Product Name</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach($stock as $p)
<tr>
<td>{{ $p->id }}</td>
<td>{{ $p->name }}</td>
<td>{{ $p->price }} </td>
<td>
<i class="fa fa-edit"></i> EDIT
<button type="button" class="btn btn-danger btn-sm delete_button"
data-toggle="modal" data-target="#DelModal"
data-id="{{ $p->id }}">
<i class='fa fa-times'></i> DELETE
</button>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div><!-- ROW-->
<div class="text-center">
{!! $stock->render() !!}
</div>
#else
<div class="text-center">
<h3>No Data available</h3>
</div>
#endif
<!-- Modal for DELETE -->
<div class="modal fade" id="DelModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel"> <i class='fa fa-trash'></i> Delete !</h4>
</div>
<div class="modal-body">
<strong>Are you sure you want to Delete ?</strong>
</div>
<div class="modal-footer">
<form method="post" action="{{ route('stock_delete') }}" class="form-inline">
{!! csrf_field() !!}
{{ method_field('DELETE') }}
<input type="hidden" name="id" class="abir_id" value="0">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-danger">DELETE</button>
</form>
</div>
</div>
</div>
</div>
#endsection
#section('scripts')
<script>
$(document).ready(function () {
$(document).on("click", '.delete_button', function (e) {
var id = $(this).data('id');
$(".abir_id").val(id);
});
});
</script>
#endsection
and this is the DashboardController.php
//Stocks
public function createStock()
{
$data['site_title'] = $this->site_title;
$data['page_title'] = "Create Stock";
//$data['currency'] = Currency::all();
return view('dashboard.stock-create',$data);
}
public function storeStock(Request $request)
{
$this->validate($request,[
'name' => 'required|unique:stocks,name',
'price' => 'required',
//'currency_id' => 'required'
]);
try {
$stock = Input::except('_method','_token');
Stock::create($stock);
session()->flash('message', 'Stock Create Successfully.');
Session::flash('type', 'success');
return redirect()->back();
} catch (\PDOException $e) {
session()->flash('message', 'Some Problem Occurs, Please Try Again!');
Session::flash('type', 'danger');
return redirect()->back();
}
}
public function showStock()
{
$data['site_title'] = $this->site_title;
$data['page_title'] = "All Stock";
$data['stock'] = Stock::orderBy('id','ASC')->paginate(100);
return view('dashboard.stock-show',$data);
}
public function editStock($id)
{
$data['stock'] = Stock::findOrFail($id);
$data['site_title'] = $this->site_title;
$data['page_title'] = 'Edit Product';
$data['stock'] = Stock::all();
return view('dashboard.stock-edit',$data);
}
public function updateStock(Request $request,$id)
{
$stocks = Stock::findOrFail($id);
$this->validate($request,[
'name' => 'required|unique:stocks,name,'.$stocks->id,
'price' => 'required',
//'currency_id' => 'required',
]);
try {
$stock = Input::except('_method','_token');
$stocks->fill($stock)->save();
session()->flash('message', 'Stock Updated Successfully.');
Session::flash('type', 'success');
return redirect()->back();
} catch (\PDOException $e) {
session()->flash('message', 'Some Problem Occurs, Please Try Again!');
Session::flash('type', 'danger');
return redirect()->back();
}
}//Stocks End
And lastly the route.php
/* Stock Route List */
Route::get('stock-create',['as'=>'stock-create','uses'=>'DashboardController#createStock']);
Route::post('stock-create',['as'=>'stock-store','uses'=>'DashboardController#storeStock']);
Route::get('stock-show',['as'=>'stock-show','uses'=>'DashboardController#showStock']);
Route::get('stock-edit/{id}',['as'=>'stock-edit','uses'=>'DashboardController#editStock']);
Route::put('stock-edit/{id}',['as'=>'stock-update','uses'=>'DashboardController#updateStock']);
You have a typo in your code,
change stock_edit to stock-edit in your view

Import data into database and show it on html table in laravel

I want to create a view in laravel that has a function to import an excel file into the database and show it in a table inside a view.
I created a controller and it imports the excel data in database but fails to show it in view.
Please Help solve my issue.
Many Thanks in advance.
Best Regards,
Dian
I am using laravel 5.5 and maatwebsite excel
public function importFileIntoDB(Request $request){
if($request->hasFile('sample_file')){
$path = $request->file('sample_file')->getRealPath();
$data = Excel::load($path, function($reader) {})->get();
if($data->count()){
foreach ($data as $key => $value) {
$arr[] = ['name' => $value->name, 'details' => $value->details];
}
if(!empty($arr)){
\DB::table('products')->insert($arr);
dd('Insert Record successfully.');
}
}
}
return back()->with($arr);
}
this is my view
#extends('frontpage')
#section('title', 'Dashboard')
#section('content_header')
<h1>Upload File From Excel Into Database</h1>
#stop
#section('content')
<div class="panel panel-primary">
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title" style="padding:12px 0px;font-size:25px;"><strong>Test - import export csv or excel file into database example</strong></h3>
</div>
<div class="panel-body">
#if ($message = Session::get('success'))
<div class="alert alert-success" role="alert">
{{ Session::get('success') }}
</div>
#endif
#if ($message = Session::get('error'))
<div class="alert alert-danger" role="alert">
{{ Session::get('error') }}
</div>
#endif
<h3>Import File Form:</h3>
<form style="border: 4px solid #a1a1a1;margin-top: 15px;padding: 20px;" action="{{ URL::to('importExcel') }}" class="form-horizontal" method="post" enctype="multipart/form-data">
<input type="file" name="import_file" />
{{ csrf_field() }}
<br/>
<button class="btn btn-primary">Import CSV or Excel File</button>
</form>
<br/>
<h3>Import File From Database:</h3>
<div style="border: 4px solid #a1a1a1;margin-top: 15px;padding: 20px;">
<button class="btn btn-success btn-lg">Download Excel xls</button>
<button class="btn btn-success btn-lg">Download Excel xlsx</button>
<button class="btn btn-success btn-lg">Download CSV</button>
</div>
<h3>Table Import List </h3>
<div style="border: 4px solid #a1a1a1;margin-top: 15px;padding: 20px;" >
print_r($arr->count());
#if(!empty($arr))
<table class="table table-striped table-hover table-reflow">
#foreach($arr as $key=>$value)
<tr>
<th ><strong> {{ $key }}: </strong></th>
<td> {{ $value }} <td>
</tr>
#endforeach
</table>
#endif
</div>
</div>
</div>
</div>
#stop
#section('css')
<link rel="stylesheet" href="/css/admin_custom.css">
#stop
#section('js')
<script> console.log('Hi! this is frontpage'); </script>
#stop
As conveyed by #gbalduzzi you need to return the data to the view as
return back()->with(['arr' => $arr]);
and access in your view as
#if(session()->has('arr'))
<table class="table table-striped table-hover table-reflow">
#php $arr = session('arr'); #endphp
#foreach($arr as $key => $value)
<tr>
<th ><strong> {{ $value['name'] }}: </strong></th>
<td>{{ $value['details'] }} <td>
</tr>
#endforeach
</table>
#endif
Docs
Change
return back()->with($arr);
with
return back()->with(['arr' => $arr]);
return back()->with('arr', $arr); // Should be equivalent
return back()->compact($arr); // Should be equivalent
The with method doesn't accept only a single value: you need to specify an array, a key and a value or use the compact method

Resources