search with ajax laravel - ajax

I need my project to have a search form, I tried with this code, but when I execute console it says:
POST http://localhost:8000/buscar 500 (Internal Server Error)
then here is my view
<div id="qnimate" class="off">
<div id="search" class="open">
<button data-widget="remove" id="removeClass" class="closeSearch" type="button">×</button>
<input type="text" placeholder="Buscar Noticias - Articulos - Reviews" id="buscar" onkeydown="keydownFunction()" onkeyup="keyupFunction()">
<button class="btn btn-lg btn-site" type="submit"><span class="glyphicon glyphicon-search"></span> Buscar</button>
<div id="resultadoBusqueda" class="col-md-12"></div>
</div>
</div>
here is my controller
public function buscar()
{
$keywords = Input::get('keywords');
$reviews = Reviews::where('estado','1')->take();
$buscarReviews = new \Illuminate\Database\Eloquent\Collection();
foreach ($reviews as $review) {
if(Str::contains(Str::lover($review->nombre), Str::lover($keywords)))
$buscarReviews->add($review);
}
return view::make('busqueda')->with('buscarReviews', $buscarReviews);
}
here is the view which shows the information
#foreach($buscarReviews as $review)
<div id="reviews" class="col-md-12">
<div class="col-md-4">
<img src="Imagenes/{{$review->logo}}" width="50">
</div>
<div class="col-md-8">
<h2>{{$review->nombre}}</h2>
<div>{!! str_limit($review->descripcion, $limit = 150, $end = '...') !!}</div>
</div>
</div>
#endforeach
here is my js
var timer;
function keydownFunction(){
timer = setTimeout(function(){
var keywords = $('#buscar').val();
if(keywords.length > 0){
$.post('/buscar', {keywords: keywords}, function(markup){
$('#resultadoBusqueda').html(markup);
});
}
}, 500);
}
function keyupFunction(){
clearTimeout(timer);
}
I don't know what is the reason that it doesn't print the information required.

you are sending post request from ajax but in your controller you are trying to get that value using get, try this code
public function buscar(Request $request)
{
$keywords = $request->keywords;
$reviews = Reviews::where('estado','1')->take();
$buscarReviews = new \Illuminate\Database\Eloquent\Collection();
foreach ($reviews as $review) {
if(Str::contains(Str::lover($review->nombre), Str::lover($keywords)))
$buscarReviews->add($review);
}
return view::make('busqueda')->with('buscarReviews', $buscarReviews);
}
also remember to change in route like this.
Route::post('buscar', 'yourController#buscar');

Related

Search Laravel Using Button

I want to search for data using a primary key, with PO as an example. Btw, I'm new to Laravel. Below is my code for my controller. I want to make the system go to the new page if the data that was searched exists(click on search button). If not, it will stay on the same page. Actually, I don't know whether my code is correct or not.
public function supplierindex(){
$supp_details = Supplier::where('PO','LIKE','%'.$searchPO.'%')->get();
return view ('frontend.praiBarcode.getweight')
->with('supp_details',$supp_details);
}
public function searchindex()
{
return view ('frontend.praiBarcode.getweight');
}
public function searchPO()
{
$searchPO = Supplier::where('PO','like',"%".$search."%")->get();
if (Supplier::where('PO','like',"%".$search."%")->exists()) {
return view('frontend.praiBarcode.getweight',compact('searchPO')); }
else {
return view('frontend.praiBarcode.index');
}
}
Below is my code in blade.php. However, the data does not come out on the screen.
<div class= "form-group">
#foreach ($supp_details as s)
<div style="font-size: 16px;" class="form-group row">
<label for="supp_name" class = "col-sm-2">PO</label>
<label for="supp_name" class = "col-sm-1">:</label>
<div class="col-sm-7">
<label> {{ $s->PO }}</label>
</div>
</div>
#endforeach
In order to pass data into the view, you have to use the second argument of the view function.
Example:
public function supplierindex(){
$supp_details = Supplier::where('PO','LIKE','%'.$searchPO.'%')->get();
return view ('frontend.praiBarcode.getweight' ,['supp_details' => $supp_details]);
}
You can use count() to check if query result is empty or not
public function searchPO()
{
$searchPO = Supplier::where('PO','like',"%".$search."%")->get();
$countsearchPO = $searchPO->count();
if ($countsearchPO ) {
return view('frontend.praiBarcode.getweight',compact('searchPO')); }
else {
return view('frontend.praiBarcode.index');
}
}
And in your blade your variable is stored in session
$supp_details = Session::get('supp_details');
#foreach ($supp_details as s)
<div style="font-size: 16px;" class="form-group row">
<label for="supp_name" class = "col-sm-2">PO</label>
<label for="supp_name" class = "col-sm-1">:</label>
<div class="col-sm-7">
<label> {{ $s->PO }}</label>
</div>
</div>
#endforeach

Laravel - Undefined variable: request in multiple submit button

In my Laravel-5.8 application, I have two submit buttons for different purposes:
Controller
public function store(StoreLeaveRequestRequest $request)
{
DB::beginTransaction();
try {
//check which submit was clicked on
if ($request->has('apply')) {
$leaverequest = new HrLeaveRequest;
$leaverequest->authorized_days = $request->authorized_days;
$leaverequest->available_days = $request->available_days;
$leaverequest->no_of_days = $days;
if($employeelinemanagerid == $employeehodid )
{
$leaverequest->line_manager_notified = 1;
$leaverequest->hod_notified = 1;
}else{
$leaverequest->line_manager_notified = 1;
}
$leaverequest->save();
$this->getLineManagerUserId();
} elseif($request->has('draft')) {
$leaverequest = new HrLeaveRequest;
$leaverequest->authorized_days = $request->authorized_days;
$leaverequest->available_days = $request->available_days;
$leaverequest->no_of_days = $days;
$leaverequest->save();
}
DB::commit();
Session::flash('success', 'Leave Request is created successfully');
return redirect()->route('service.leave_requests.index');
}
catch (Exception $exception)
{
dd($exception->getMessage());
DB::rollback();
Session::flash('error', 'Action failed!');
return redirect()->route('service.leave_requests.index');
}
}
view
<form action="{{route('service.leave_requests.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{csrf_field()}}
<div class="card-body">
<div class="form-body">
<div class="row">
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" name="apply" class="btn btn-primary">Submit</button>
<button type="submit" name="draft" class="btn btn-warning">Save as Draft</button>
</div>
</form>
I used name="apply" for
($request->has('apply'))
and name="draft" for
($request->has('draft'))
When I click on any of the submit buttons, I got this error:
"Undefined variable: request"
I tried to check, I don't know where the error is coming from
Where did I get it wrong?
Kindly assist.
Thanks

Laravel Maatwebsite excel

I need your help. I don't know how to import the excel file. I mean I don't understand where to put this users.xlsx and how to get its directory
public function import()
{
Excel::import(new UsersImport, 'users.xlsx');
return redirect('/')->with('success', 'All good!');
}
its simple on mattwebsite you need a controller like below :
public function importExcel(Request $request)
{
if ($request->hasFile('import_file')) {
Excel::load($request->file('import_file')->getRealPath(), function ($reader) {
foreach ($reader->toArray() as $key => $row) {
// note that these fields are completely different for you as your database fields and excel fields so replace them with your own database fields
$data['title'] = $row['title'];
$data['description'] = $row['description'];
$data['fax'] = $row['fax'];
$data['adrress1'] = $row['adrress1'];
$data['telephone1'] = $row['telephone1'];
$data['client_type'] = $row['client_type'];
if (!empty($data)) {
DB::table('clients')->insert($data);
}
}
});
}
Session::put('success on import');
return back();
}
and a view like this :
<form
action="{{ URL::to('admin/client/importExcel') }}" class="form-horizontal" method="post"
enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<label class="control-label col-lg-2">excel import</label>
<div class="col-lg-10">
<div class="uploader"><input type="file" name="import_file" class="file-styled"><span class="action btn btn-default legitRipple" style="user-select: none;">choose file</span></div>
</div>
</div>
<button class="btn btn-primary">submit</button>
</form>
and finally a route like below :
Route::post('admin/client/importExcel', 'ClientController#importExcel');

Getting a vue form to go to the next page after submit in laravel

I'm using both laravel and vue and I'm trying to get my vue form to go to another page when I've submitted, but the problem is that once it's submitted it refreshes and goes back to the page it's on instead of the other page.
When I check my network tab in the dev tools, it posted to the right page but it doesn't show up in the browser
This is my vue
<template>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Example Component</div>
<div class="card-body">
I'm an Supplier Code Selection component.
<br>
<form #submit.prevent="submit">
<label for="parent-product">Parent Product</label>
<select name="parent-product" id="parent-product" class="form-control" v-model="selected_parent">
<option>Please select your code</option>
<option v-for="product in products" :value="product.id">
{{ product.supplier_code }}
</option>
<option v-for="child in children" :value="child.id">
{{ child.supplier_code }}
</option>
</select>
<input type="submit" class="btn btn-primary" value="Submit">
</form>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
props: [
'products',
'children',
'selected_parent'
],
mounted() {
console.log('Component mounted.')
},
methods: {
submit(){
var formData = new FormData();
console.log('this is the select box - '+this.selected_parent);
formData.append('parent-product', this.selected_parent);
return axios.post('/add-to-cart/'+this.selected_parent, formData);
},
},
}
</script>
My route
Route::any('/add-to-cart/{id}', 'PublicController#getAddToCart')->name('product.addToCart');
My controller function
public function getAddToCart(Request $request, $id)
{
$menus_child = Menu::where('menu_id', 0)->with('menusP')->get();
$contacts = Contact::all();
$product = Product::find($id);
$supplier_code = $request->supplier_code;
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new Cart($oldCart);
$cart->add($product, $product->id, $supplier_code);
$request->session()->put('cart', $cart);
return view('public.shopping-cart', ['products' => $cart->items, 'totalPrice' => $cart->totalPrice, 'menus_child' => $menus_child, 'contacts' => $contacts, 'supplier_code' => $supplier_code]);
}
You could just add a location if the axios call returns success. Ps. untested code.
methods: {
submit(){
var formData = new FormData();
console.log('this is the select box - '+this.selected_parent);
formData.append('parent-product', this.selected_parent);
return axios.post('/add-to-cart/'+this.selected_parent, formData)
.then(response => { location: '/'});
},
I found my issue. I forgot to change
return view('public.shopping-cart', compact('supplier_code'));
to
return ['redirect' => route('product.shoppingCart')];
in my laravel controller function

how search between date using post in codeignitier

Dear Expert need Help first see my view code in codeigniter :
<div class="form-group">
<label for="tglawal" class="col-sm-2 control-label">Periode</label>
<div class="col-sm-3">
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="date" class="form-control" name="tglawal" id="tglawal">
</div>
</div>
<div class="col-sm-3">
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="date" class="form-control" name="tglakhir" id="tglawal1">
</div>
</div>
</div>
and this my model code :
private function _get_datatables_query()
{
//add custom filter here
if($this->input->post('tglawal'))
{
$this->db->where('b.tglawal', $this->input->post('tglawal'));
}
if($this->input->post('tglakhir'))
{
$this->db->where('b.tglakhir', $this->input->post('tglakhir'));
}
}
public function get_datatables()
{
$this->_get_datatables_query();
if($_POST['length'] != -1)
$this->db->limit($_POST['length'], $_POST['start']);
$query = $this->db->get();
return $query->result();
}
and my controller if i get the important code is:
public function index()
{
$this->load->helper('url');
$this->load->helper('form');
$this->load->view('infokunjungan_view', $data);
}
else redirect(base_url());
}
public function ajax_list()
{
$list = $this->Infokunjungan->get_datatables();
$data = array();
$no = $_POST['start'];
foreach ($list as $infokunjungan) {
$no++;
$row = array();
$row[] = "<td style='vertical-align:middle'><center>{$no}<center></td>";
$row[] = "<td style='font-size:9px; vertical-align:left;'>{$infokunjungan->tglawal}<center></td>";
$row[] = "<td style='font-size:9px; vertical-align:left;'>{$infokunjungan->tglakhir}<center></td>";
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->Infokunjungan->count_all(),
"recordsFiltered" => $this->Infokunjungan->count_filtered(),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
the problem is if searching between two date tglawal and tglakhir
im using between 2016-12-04 and 2016-12-04 output display will empty
but if using between 2016-12-04 and 2016-12-06 output success where is my problem or maybe im using where or i have to use like?
You need to use the >= and <= operator.
In your model try the below.
if($this->input->post('tglawal'))
{
$this->db->where('b.tglawal >=', $this->input->post('tglawal')); //assuming this is your begining (from) date
}
if($this->input->post('tglakhir'))
{
$this->db->where('b.tglakhir <=', $this->input->post('tglakhir')); //assuming this is your end(to) date
}
The above will search for the between dates including the dates selected.
Use the operator depending on the beginning and ending variable.

Resources