Search results to show in blade using ajax and laravel - laravel

I have a search place for costumers to search the product which will be displayed in blade. I am using ajax and laravel. Here is my code as much as I wrote. The query works well and when I print $filter I can see the results.
$('.gotosearch').on('click' , function() {
var search = $(this).val()
var inpvalue = $('.form-control').val()
$.ajax({
url:'/searchproducts',
type:'post',
data: {
inpvalue,
"_token" : token
},
success:function(r) {
console.log(r)
}
})
})
Route::post('/searchproducts' , 'ProductController#searchproducts');
function searchproducts(Request $search) {
$filter = ProductModel::where('Product_Name','LIKE', $search->inpvalue.'%')->get();
}

You can use response()->json in you controller
As per Laravel documentation
The json method will automatically set the Content-Type header to
application/json, as well as convert the given array to JSON using the
json_encode PHP function:
return response()->json([
'name' => 'Abigail',
'state' => 'CA'
]);
Try this:
return response()->json($filters->toArray());
https://laravel.com/docs/5.8/responses#json-responses

try this:
// search text
<div class="form-group">
<input type="text" id="search" name="search" class="form-control" id="exampleInputEmail" aria-describedby="emailHelp" placeholder="Search" value="{{ old('accountNo') }}" style="font-size:20px;font-weight:bold;" required>
</div
// search result
<div id="getResult" class="panel panel-default" style="width:400px; height: 150px; overflow-y:auto; position:absolute; left:50px; top:180px; z-index:1; display:none;background-color:white">
<div id="getList"></div>
</div>
//ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#search').keyup(function(){
var search = $('#search').val();
if(search==""){
$('#getResult').css('display', 'none').hide();
}
else{
var getQueries = "";
$.get("{{ url('/') }}" + '/search/' + search,
{search:search},
function(data){
if(data){
$('#getResult').css('display', 'block');
}else{
$('#getResult').css('display', 'none')
}
if(search == ''){
$('#getResult').css('display', 'none').hide();
}else{
$.each(data, function (index, value){
var id=value.ID;
getQueries += '<ul style="margin-top:3px; list-style-type:none;">';
getQueries += '<a href={{ url("add-contribution-amount")}}' +'/'+ value.id + '>' + value.fullname +' | '+value.accountno + '</a>';
getQueries += '</ul>';
});
$('#getList').html(getQueries );
}
})
}
});
</script>
//controller
public function CustomerSearch($getSearch){
$search = $getSearch;
$members = DB::table('tblcustomers')
->where('accountno', 'like', "%$search%")
->select('id','branchID', 'fullname', 'savingstype', 'accountno')
->orderby('id','asc')
->get();
return $members;
}
//route
Route::get('/search/{searchQuerys?}', 'ContributionController#CustomerSearch');

Related

autocomplete function not working for mobile view

Hello I am creating searching task in my project it works fine for destop view but when i open my website in mobile and press key then keypad is open and close within second what is problem in my code. What is mistake? why code is not working in mobile view?
//html
<form class="ps-search--header" action="#" method="post">
{{ csrf_field()}}
<input class="form-control" type="text" placeholder="Search Product…" id="product_name">
<button><i class="ps-icon-search"></i></button>
<div id="product_list"></div>
</form>
//controller
public function fetch(Request $request)
{
if($request->get('query'))
{
$query = $request->get('query');
$data = DB::table('products')
->where('product_name', 'LIKE', "%{$query}%")
->get();
$output = '<ul class="dropdown-menu" style=" display:block; ;width:100%">';
foreach($data as $row)
{
$name=[];
$name=explode(" ",$row->product_name);
$output .= '
<li>'.$row->product_name.'</li>
';
}
$output .= '</ul>';
echo $output;
}
}
//autocomplete
$('#product_name').keyup(function(){
var query = $(this).val();
if(query != '')
{
var _token = $('input[name="_token"]').val();
$.ajax({
url:"/autocomplete",
method:"get",
data:{query:query, _token:_token},
success:function(data){
$('#product_name').fadeIn();
$('#product_list').html(data);
}
});
}
});
$(document).on('click', 'li', function(){
$('#product_name').val($(this).text());
$('#product_list').fadeOut();
});
This kind of keyup wold not work sometimes with mobile which work great on desktop
You can use this Keyup on Your autocomplete function its work on both check the code bellow
$('#product_name').on('keyup input', function(e){
if(e.keyCode == 13) {
$("input").blur();
}
var query = $(this).val();
if(query != '')
{
var _token = $('input[name="_token"]').val();
$.ajax({
url:"/autocomplete",
method:"get",
data:{query:query, _token:_token},
success:function(data){
$('#product_name').fadeIn();
$('#product_list').html(data);
}
});
}
});
$(document).on('click', 'li', function(){
$('#product_name').val($(this).text());
$('#product_list').fadeOut();
});

How can I fetch autocomplete data into their respected element using Ajax and Laravel?

Here is my problem.
I'm trying to fetch the data from an auto-completing text-box.
There are two text-boxes:
Region and province.
I have successfully fetched the data on the text-box having region as name.
My problem is, it gives the same value to the next text-box having province as name.
In my Laravel blade I have this code:
<input id="region" type="text" class="form-control" name="region" value="" required autofocus>
<div id="regionList"> </div>
<input id="province" type="text" class="form-control" name="province" value="" required autofocus>
<div id="provinceList"> </div>
I have also a javascript file named auto-complete
$(document).ready(function() {
$('#region').keyup(function() {
var region = $(this).val();
if (region != '')
{
var _token = $('input[name="_token"]').val();
$.ajax({
url: "register/showRegion",
method: "POST",
data: { region: region, _token: _token },
success: function(data)
{
$('#regionList').fadeIn();
$('#regionList').html(data);
}
});
}
});
$(document).on('click', 'li', function() {
$('#region').val($(this).text());
$('#regionList').fadeOut();
});
$('#province').keyup(function() {
var province = $(this).val();
if (province != '')
{
var _prov_token = $('input[name="_token"]').val();
$.ajax({
url: "register/showProvince",
method: "POST",
data: { province: province, _token: _token },
success: function(data)
{
$('#provinceList').fadeIn();
$('#provinceList').html(data);
}
});
}
});
$(document).on('click', 'li', function() {
$('#province').val($(this).text());
$('#provinceList').fadeOut();
});
});
And on my routes I included this
Route::post('/register/showRegion', 'LocationController#showRegion');
Route::post('/register/showProvince', 'LocationController#showProvince');
And on my controller is this
public function index() {
return view('auth.register');
}
function showRegion(Request $request)
{
if ($request->get('region'))
{
$region = $request->get('region');
$regions = Refregion::where('regDesc', 'LIKE', "$region%")->get();
$output = '<ul class="dropdown-menu" style="display:block; position:absolute;">';
foreach($regions as $region)
{
$output .= '<li>'.$region->regDesc.'</li>';
}
$output .= '</ul>';
echo $output;
}
}
function showProvince(Request $request)
{
if ($request->get('province'))
{
$province = $request->get('province');
$province = Refprovince::where('provDesc', 'LIKE', "province%")->get();
$output = '<ul class="dropdown-menu" style="display:block; position:absolute;">';
foreach($provinces as $province)
{
$output .= '<li>'.$province->provDesc.'</li>';
}
$output .= '</ul>';
echo $output;
}
}
I'm trying to figure out why it gives the same value to the other text-box "province" when I have selected region.
Can someone help me with this, or at least explain to me why this happen?
Thank you
change it
$(document).on('click', 'li', function() {
$('#region').val($(this).text());
$('#regionList').fadeOut();
});
on this
$('#regionList').on('click', 'li', function() {
$('#region').val($(this).text());
$('#regionList').fadeOut();
});
and change it
$(document).on('click', 'li', function() {
$('#province').val($(this).text());
$('#provinceList').fadeOut();
});
on this
$('#provinceList').on('click', 'li', function() {
$('#province').val($(this).text());
$('#provinceList').fadeOut();
});

How to get value of Selected items of Select2 when submitted?

What options I should set to get the value of the options when I submit the form?
I am using Select2. I have given the code I have to setup the select2, controller that returns the data, the html code that renders the element.
Html Code to add the select2 element:
<div class="form-group row"><label class="col-lg-2 col-form-label">Keyword</label>
<div class="col-lg-10">
<select class="form-control w-50" name="keywords[]" id="keyword" multiple="multiple">
</select>
<span class="form-text m-b-none">One or multiple keywords</span>
</div>
</div>
Datasource is an Ajax call:
$(document).ready(function() {
$('#keyword').select2({
tags: true,
tokenSeparators: [',', ' '],
placeholder: 'Select keyword',
ajax: {
url: 'https://rankypro.dev/app/json/keywords',
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
id: item.id
}
})
};
},
cache: true
}
});
Controller:
public function getKeywords(Request $request){
$search = $request->search;
if($search == ''){
$keywords = Term::orderby('name','asc')
->select('id','name')
->where('taxonomy','keyword')
->limit(5)
->get();
}else{
$keywords = Term::orderby('name','asc')->select('id','name')
->where('taxonomy','keyword')
->where('name', 'like', '%' .$search . '%')
->limit(5)
->get();
}
$results = array();
foreach($keywords as $keyword){
$results[] = array(
"id"=>$keyword->id,
"text"=>$keyword->name
);
}
echo json_encode($results);
exit();
}
I am testing with:
public function store(Request $request)
{
dd($request->keywords);
}
I get the following:
array:2 [
0 => "Tools"
1 => "SEO"
]
I actually need ids of the keywords. Would you please give some hints how can I get that.
I think their is some issue in rendering data. Try to replace
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
id: item.id
}
})
};
},
With
processResults: function (data) {
return {
results: data.item
};
},
select2 automatically render id and name.

RE - Laravel: Auto fill input after selecting value from dropdown

Im having trouble to retrieve data into input box right after user select from dropdown. Any suggestion? Last suggest was not working.
internalaudit.blade.php
<div class="form-group">
{!! Form::label('text', 'Doc No', ['class' => 'col-lg-3 control-label']) !!}
<div class="col-lg-10">
<select name="docNo" id="docNo" class="form-control" style="width:250px">
#foreach ($soplists as $soplist)
<option value="{{ $soplist->id }}">{{ $soplist->doc_no }}</option>
#endforeach
</select>
</div>
</div>
<input type="text" class="form-control" name="rev_no" id="rev_no">
<input type="text" class="form-control" name="title" id="title">
Ajax
<script>
$('#docNo').change(function() {
var id = $(this).val();
var url = '{{ route("getDetails", ":id") }}';
url = url.replace(':id', id);
$.ajax({
url: url,
type: 'get',
dataType: 'json',
success: function(response) {
if (response != null) {
$('#rev').val(response.rev_no);
$('#title').val(response.title);
}
}
});
});
Controller
public function internalAudit()
{
/*Generate number*/
$query = Cars::latest()->first(); //get last query
$validators = User::all();
$departments = Department::all();
$isolists = isoList::all();
$soplists = sopList::all();
$ex = explode('/', $query['iaCarRefNo']); //explode last number from DB
$type = strtoupper(Request::segment(2)); //get type from url
if (empty($query->iaCarRefNo)) {
$number = '1';
$nextNumber = 'PLW' . '/' . date('y') . $type . '/' . sprintf("%03d", $number);
} else {
$number = $ex[2] + 1;
$nextNumber = 'PLW' . '/' . date('y') . $type . '/' . sprintf("%03d", $number);
}
return view('cars.internalaudit', compact('nextNumber', 'validators', 'departments', 'isolists', 'soplists'));
}
public function getDetails($id = 0)
{
$data = sopList::where('doc_no', $id)->first();
return response()->json($data);
}
Route
Route::get('get/details/{id}', 'internalAuditController#getDetails')->name('getDetails');
Route::get('/internalaudit', 'internalAuditController#internalAudit');
Route::post('/internalaudit', ['as' => 'internalaudit.store', 'uses' => 'internalAuditController#store']);
Database sop_list table image link
https://ibb.co/SwkJhLc
Dropdown and input image
https://ibb.co/0VN3Z2y
Network tab
https://ibb.co/56w5BLD
Accoding to your console.log there are 2 errors $.ajax is not function and $.(...) datetimepicker is not function beacuse of those errors, now your ajax does not work therefore you need to fix those issues first. Once you fix those issues you will be able to send ajax request and update input fileds.
To fix first problem, download the regular (compressed or not) version of jQuery and include it in your project.
To fix second problem, download relevant datetimepicker and include in your project same like jQuery.
After that update #rev selector to #rev_no
$('#rev_no').val(response.rev_no);
Also use laravel helper function instead echo json_encode();
return response()->json($data);
In your table there is no record for doc_no = 3, in your blade you're using $soplist->id
<option value="{{ $soplist->id }}">{{ $soplist->doc_no }}</option>
So do the same thing on controller,
$data = sopList::where('id', $id)->first();
Or
$data = sopList::find($id);
You gave a wrong id to response, also you should give an id to title input.
<input type="text" class="form-control" name="title" id="title">
<script>
$(document).ready(function(){
$(document).on('change','#docNo',function(){
var id = $(this).val();
var url = '{{ route("getDetails", ":id") }}';
url = url.replace(':id', id);
$.ajax({
type: 'get',
url: url,
dataType: 'json',
success: function(response) {
$('#rev_no').val(response.rev_no);
$('#title').val(response.title);
}
});
});
});
</script>

laravel search - returning all results even if no match and make delay to ajax

I have a problem with my search.
Problem 1
Currently if I type in the field it is searching however the search never ever stops, so if I type hello, it will make about 500 requests within a minute.
Problem 2
I am searching in film table to find matching 'title' as well as find business name corresponding to business_id in business table.
Problem 3
Each time request is made it brings back master page again i.e. loading all js and css (which might be why it is making so many requests?) but if I don't extend master, result blade doesn't work.
however even if I input 'e' it brings me back 'guardians of the galaxy' which doesn't have 'e' My thoughts are that it is searching throught business table as well somehow. They have both eloquent one to one relationships
Controller:
public function cinema_search($cinema_value) {
$cinema_text = $cinema_value;
if ($cinema_text==NULL) {
$data = Film::all();
} else {
$data = Film::where('title', 'LIKE', '%'.$cinema_text.'%')->with('business')->get();
}
return view('cinemasearch')->with('results',$data);
}
Form::
<form id="cinema_display">
<div class="form-group">
<input type="text" class="form-control" id="search_cinemas" onkeyup="search_cinema(this.value);" placeholder="Search film">
</div>
<div id="show"
</div>
</div>
</form>
ajax:
function search_cinema(cinema_value) {
$.ajax({
url: '/cinemasearch/' + cinema_value,
type: 'post',
dataType: 'html',
success: function(data) {
$('#show').append(data);
$('.se-pre-con').fadeOut('slow', function () {
$(".container").css({ opacity: 1.0 });
});
},
error: function(data) {
},
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
}
cinemasearch.blade(results):
#extends('master') #section('title', 'Live Oldham') #section('content')
#section('content')
<table style="width:100%">
#if (isset($results) && count($results) > 0)
#foreach( $results as $film )
<tr>
<td>{{ $film->business->name }}</td>
<td>{{ $film->title }}</td>
<td>{{ $film->times}}</td>
</tr>
#endforeach
#endif
</table>
#endsection
function search_data(search_value) {  
$.ajax({
        url: '/searching/' + search_value,
        type: 'post',
        dataType: 'html',
        success: function(data) {
            $('#show_search_result').append(data);
            $('.se-pre-con').fadeOut('slow', function () {
$(".container").css({ opacity: 1.0 });
            });
        },
        error: function(data) {
            $('body').html(data);
        },
        headers: {
        'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
        }
    });
}
function tram_stops(tram_value) {
    $.ajax({
        url: '/tramsearch/' + tram_value,
        type: 'post',
        dataType: 'html',
        success: function(data) {
            $("#display").html(data);
            var tram_value = tram_value;
        },
        error: function(data) {
            
        },
        headers: {
        'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
        }
    });
}
/*
setInterval(tram_stops, (30 * 1000));
*/
function search_cinema(cinema_value) {
    $.ajax({
        url: '/cinemasearch/' + cinema_value,
        type: 'post',
        dataType: 'html',
        success: function(data) {
                var items = JSON.parse(data);
                var showElement = $('#show');
                showElement.html('');
                $.each(data, function() {
                   showElement.append(this.title +' '+ this.times+'<br />');
                });
        },
        error: function(data) {
        },
        headers: {
        'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
        }
    });
}
You are returning the wrong response type from cinema_search. Ajax expects a JsonResponse, not what the view helper returns which is \Illuminate\Http\Response. Put your search results in:
return response()->json(['results' => $data]);
to start with if you just want the data. If you want to actually return the rendered view file, you would need to do:
return response()->json(['results' => view('cinemasearch')->with('results',$data)->render()]);
then inject that into your DOM. The problem with rendering server side is nothing is bound client side so if you have any interaction requiring JS, you'll need to create those manually in your success callback.
Problem 1:
Remove the keyUp event in your html and add an event in Jquery.
Your HTML structure is not correct
This:
<form id="cinema_display">
<div class="form-group">
<input type="text" class="form-control" id="search_cinemas" onkeyup="search_cinema(this.value);" placeholder="Search film">
</div>
<div id="show"
</div>
</div>
</form>
Should be:
<form id="cinema_display">
<div class="form-group">
<input type="text" class="form-control" id="search_cinemas" onkeyup="search_cinema(this.value);" placeholder="Search film">
<div id="show">
</div>
</div>
</form>
Then again you should consider to remove the onkeyup event. And change add it in Jquery to something like this:
Problem 2 & 3: I would recommend a raw Query and return an json instead of a view. And you shouldn't check if($cinema_text === NULL) this won't be the case ever. Unless you put NULL in your url and even then it will be an String and not NULL and if('NULL' === NULL) returns false look at this post for the diff of == and ===.
public function cinema_search($cinema_value) {
$cinema_text = $cinema_value;
if (empty($cinema_text)) {
$data = Film::all();
} else {
$data = DB::select('*')
->from('films')
->join('businesses', 'businesses.id', '=', 'films.business_id')
->where('films.title', 'LIKE', '%'.$cinema_text.'%')
->orWhere('bussiness.title', 'LIKE', '%'.$cinema_text.'%')
->get();
}
return response()->json(['results' => $data]);
}
Then in your JavaScript do something like this:
$( document ).ready(function() {
console.log( "ready!" );
$( "#search_cinemas" ).change(function() {
search_cinema(this.value);
console.log( "New value"+this.value+"!" );
});
function search_cinema(cinema_value) {
console.log('setup ajax');
$.ajax({
url: '/cinemasearch/' + cinema_value,
type: 'post',
success: function(data) {
console.log('success!');
var showElement = $('#show');
showElement.html('');
$.each(items, function() {
showElement.append(this.title +' '+ this.times+'<br />');
});
},
error: function(data) {
console.log(data);
},
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
}
});

Resources