Problem using Laravel when I add a record - ajax

Great to know you!
I have a problem when I use Laravel to make book bus tickets online system :((. I import *.sql by phpMyadmin so I don't create file migrate.
This is lichtrinh table
Everything is well (1st record and 2nd record my application working well) but until I add 3rd record to table, ajax() alert ('Not submit') Althought I just add new record
My file js
$(document).ready(function () {
$('#btn-submit').click(function (e) {
e.preventDefault();
$username = $('#username').val();
$pass = $('#pass').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$.ajax({
url: "/login",
type: "POST",
data: {
username: $username,
pass: $pass
},
success: function (data) {
if (data == '') {
window.location = "/ve/banve"
} else {
$('.toast-container').empty();
$('.toast-container').append(data);
$('.toast').each(function (indexInArray,
valueOfElement) {
var toast2 = new bootstrap.Toast($(this));
toast2.show();
});
}
},
error: function () {
alert("Not submit")
},
});
});
});
My controller
public function findLichTrinh(Request $request)
{
$lichtrinhs = LichTrinh::where('id_tuyen', $request->id_tuyen)->where('ngaydi', $request->ngaydi)->get();
$output = "";
if (!empty($lichtrinhs)) {
foreach ($lichtrinhs as $lichtrinh) {
$output .= '<div class="main-item-roundbus m-2 able-cursor">
<div class="main-item-title d-inline-flex justify-content-around align-items-center">
<span class="text-white">' . $lichtrinh->giodi . '</span>
<span class="text-white border border-3 p-1" style="border-radius: 5px;">' . $lichtrinh->xes->bienso . '</span>
</div>
<div class="px-2">
<span style="font-size: 17px;" class="fw-bold text-danger text-center">' . $lichtrinh->tuyens->name_tuyen . '</span>
<br>
<span style="font-size: 17px;">Ghế trống: 10</span><br>
<span style="font-size: 17px;">Gía: 100 000 VNĐ</span><br>
</div>
</div>';
}
} else {
$output = '<h1>Not Found</h1>';
}
return $output;
}
My route
Route::get('/ve/banve/lichtrinh', 'App\Http\Controllers\VeController#findLichTrinh');
Thank you very much! Please help me. I'm so sorry, I know my English is not well

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();
});

Search results to show in blade using ajax and 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');

Laravel 5: When store data to database The server responded with a status of 405 (Method Not Allowed)

I m new in Laravel and trying to add data to the database via ajax, but it throws this message: "The server responded with a status of 405 (Method Not Allowed)" I define two routes for this one is for form page
Route::get('/create/{id}', 'Participant\ParticipantProjectDefinitionController#create')->name('participant.project-definition.create');
and other route to save this data like this:
// To save Project definition Data
Route::get('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
And the Ajax code I'm using is this:
function storeDefinitionFormData(addUrl, token, baseUrl){
$('#create_project_definition_data').click(function(e){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
e.preventDefault();
var form_fields = [];
var counter = 0;
$('.form-group').each(function(){
var values = {
'field_name' : $('#field_name_' + counter).val(),
'field_data' : $('#field_data_' + counter).val(),
};
form_fields.push(values);
counter++;
});
$.ajax({
type: 'POST',
dataType: 'JSON',
url: addUrl,
data: {
'_token' : token,
'customer_name' : $('#field_name_0').val(),
'customer_name' : $('#field_data_0').val(),
// 'form_fields' : form_fields
},
success: function(data){
alert('done');
window.location = baseUrl;
},
error: function(data){
alert('fail');
if(data.status == 422){
errors = data.responseJSON.errors; // => colllect all errors from the error bag
var fieldCounter = 0;
$('.help-block').show();
$('.validation').empty(); // => clear all validation
// display the validations
$('.validation').css({
'display' : 'block'
});
// iterate through each errors
$.each(errors, function(key, value){
if(key.includes('form_fields.')){
var field_errors = key.split('.');
var field_error = field_errors[2] + "_" + field_errors[1];
$('#' + field_error + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
}
$('#' + key + '_help').hide();
$('#' + key + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
});
}
}
});
});
}
Controller code
/**
* create project Definition Form
*
*/
public function create(request $request, $id){
$ProjectDefinitionFields = ProjectDefinitionFields::all();
$ProjectDefinitionFieldRow = ProjectDefinitionFields::where('project_definition_id','=', $id)->get();
// dd($ProjectDefinitionFieldRow);
return view('participants.project_definition.create', ['ProjectDefinitionFieldRow' => $ProjectDefinitionFieldRow]);
}
public function store(request $request, $id, User $user, ProjectDefinitionFields $ProjectDefinitionFields){
$project = ProjectDefinitionFields::find('field_id');
$count = ProjectDefinitionFields::where('project_definition_id','=', $id)->count();
$pd_id = ProjectDefinitionFields::where('project_definition_id','=', $id)->get();
for($i=0;$i<$count;$i++){
$data[]= array (
'field_name'=>$request->get('field_name_'.$i),
'field_data'=>$request->get('field_data_'.$i),
'user_id' => Auth::user()->id,
// 'user_id' => $request->user()->id,
'project_definition_id' => $pd_id,
// 'field_id' => $projectDefinitionFields->id,
);
}
$project_data = ProjectDefinitionData::create($data);
if($project_data){
return response()->json($project_data);
}
}
Model
on ProjectDefinition
public function formFields(){
// return $this->hasMany('App\Model\ProjectDefinitionFields');
return $this->belongsTo('App\Model\ProjectDefinitionFields');
}
on projectDefinitionFields
public function projectDefinition(){
return $this->belongsTo('App\Model\ProjectDefinition');
}
This is my create.blade.php
<form id="create_project_definition_data_form" enctype="multipart/form-data" >
#csrf
{{ method_field('PUT') }}
<?php $count = 0; ?>
#foreach($ProjectDefinitionFieldRow as $value)
<div class="row">
<div class="form-group col-md-12" id="form-group">
<div class="row">
<label for="definition_data_<?php echo $count; ?>" class="col-sm-2 col-md-2 col-form-label" id="field_name_<?php echo $count; ?>" name="field_name_<?php echo $count; ?>[]" value="{{$value->field_name }}">{{$value->field_name }}</label>
<div class="col-sm-10 col-md-10">
{{-- textbox = 1
textarea = 0 --}}
<<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?> class="form-control" name="field_data_<?php echo $count; ?>[]" placeholder="Enter project definition_data" id="field_data_<?php echo $count; ?>" aria-describedby="field_data_help"></<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?>>
<small id="field_data_help_<?php echo $count; ?>" class="form-text text-muted help-block">
Optional Field.
</small>
<span id="field_data_error_<?php echo $count; ?>" class="invalid-feedback validation"></span>
</div>
</div>
</div>
</div>
<hr />
<?php $count++; ?>
#endforeach
<div class="text-center">
<button type="submit" class="btn btn-primary" id="create_project_definition_data">Create Project Defination Data</button>
</div>
</form>
#section('scripts')
<script src="{{ asset('js/participants/project-definition.js') }}"></script>
<script>
// on document ready
$(document).ready(function(){
var baseUrl = "{{ url('/') }}";
var indexPdUrl = "{{ route('participant.projectDefinition') }}";
var token = "{{ csrf_token() }}";
{{-- // var addUrl = "{{ route('participant.project-definition.create') }}"; --}}
storeDefinitionFormData(token, baseUrl);
// console.log(addUrl);
});
</script>
ERROR
Request URL:http://127.0.0.1:8000/participant/project-definition/create/2kxMQc4GvAD13LZC733CjWYLWy8ZzhLFsvmOj3oT
Request method:POST
Remote address:127.0.0.1:8000
Status code: 405 Method Not Allowed
Version:HTTP/1.0
Add method attribute in form
method="post"
Change your route from
Route::get('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
to
Route::post('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
Firstly, you should post here what's your problem and where's your problem we don't need to see all of your code to solve a basic problem.
Your form should be this:
<form id="create_project_definition_data_form" enctype="multipart/form-data" method='post'>
#csrf
<?php $count = 0; ?>
#foreach($ProjectDefinitionFieldRow as $value)
<div class="row">
<div class="form-group col-md-12" id="form-group">
<div class="row">
<label for="definition_data_<?php echo $count; ?>" class="col-sm-2 col-md-2 col-form-label" id="field_name_<?php echo $count; ?>" name="field_name_<?php echo $count; ?>[]" value="{{$value->field_name }}">{{$value->field_name }}</label>
<div class="col-sm-10 col-md-10">
{{-- textbox = 1
textarea = 0 --}}
<<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?> class="form-control" name="field_data_<?php echo $count; ?>[]" placeholder="Enter project definition_data" id="field_data_<?php echo $count; ?>" aria-describedby="field_data_help"></<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?>>
<small id="field_data_help_<?php echo $count; ?>" class="form-text text-muted help-block">
Optional Field.
</small>
<span id="field_data_error_<?php echo $count; ?>" class="invalid-feedback validation"></span>
</div>
</div>
</div>
</div>
<hr />
<?php $count++; ?>
#endforeach
<div class="text-center">
<button type="submit" class="btn btn-primary" id="create_project_definition_data">Create Project Defination Data</button>
</div>
</form>
You should use 'post' method when you're creating a something new, this is safer than using 'get' method. so change route method too.
Route::post('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
also, in your 'ParticipantProjectDefinitionController->store()' function has
$id, User $user, ProjectDefinitionFields $ProjectDefinitionFields parameters but your router not. We can fix it like this:
Route::post('/store-project-definition-data/{id}/{user}/{ProjectDefinitionFields}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
That means you should pass all of them to your controller.
Soo we can edit your ajax call like this:
function storeDefinitionFormData(addUrl, token, baseUrl){
$('#create_project_definition_data').click(function(e){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
e.preventDefault();
var form_fields = [];
var counter = 0;
$('.form-group').each(function(){
var values = {
'field_name' : $('#field_name_' + counter).val(),
'field_data' : $('#field_data_' + counter).val(),
};
form_fields.push(values);
counter++;
});
$.ajax({
type: 'POST',
dataType: 'JSON',
url: addUrl,
data: { // $id, User $user, ProjectDefinitionFields $ProjectDefinitionFields
'_token' : token,
'id' : 'your_id_field',
'user' : '{{ Auth::user() }}',
'ProjectDefinitionFields' : 'your_definition_fields' // you need to pass type of 'ProjectDefinitionFields'
},
success: function(data){
alert('done');
window.location = baseUrl;
},
error: function(data){
alert('fail');
if(data.status == 422){
errors = data.responseJSON.errors; // => colllect all errors from the error bag
var fieldCounter = 0;
$('.help-block').show();
$('.validation').empty(); // => clear all validation
// display the validations
$('.validation').css({
'display' : 'block'
});
// iterate through each errors
$.each(errors, function(key, value){
if(key.includes('form_fields.')){
var field_errors = key.split('.');
var field_error = field_errors[2] + "_" + field_errors[1];
$('#' + field_error + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
}
$('#' + key + '_help').hide();
$('#' + key + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
});
}
}
});
});
}
before try it, I'll give you a advice. Read whole documentation and review what others do on github or somewhere else
Route::match(['GET','POST'],'/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
You can try this Route it will resolve 405

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