Live Search using Ajax and Getting Error "500 (Internal Server Error)" on Laravel 5.8 - ajax

I was following tutorial to Live Search using ajax on Laravel, but in the implementation I get error:
GET http://localhost:8000/search?search=k 500 (Internal Server Error)
I was following this tutorial 3 times but always getthis same error. I modified like this:
<!DOCTYPE html>
<html>
<head>
<meta name="_token" content="{{ csrf_token() }}">
<title>Live Search</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="panel panel-default">
<div class="panel-heading">
<h3>Products info </h3>
</div>
<div class="panel-body">
<div class="form-group">
<input type="text" class="form-controller" id="search" name="search">
<input type="hidden" name="_method" value="POST">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</div>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>ID</th>
<th>Product Name</th>
<th>Description</th>
<th>Price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</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>
<script type="text/javascript">
$.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });
</script>
</body>
</html>
my controller:
public function search(Request $request)
{
if($request->ajax()) {
$output="";
$products=DB::table('products')->where('title','LIKE','%'.$request->search."%")->get();
if($products) {
foreach ($products as $key => $product) {
$output.='<tr>'.
'<td>'.$product->id.'</td>'.
'<td>'.$product->title.'</td>'.
'<td>'.$product->description.'</td>'.
'<td>'.$product->price.'</td>'.
'</tr>';
}
return Response($output);
}
}
}
I was trying this code for 3 different database and always get the same error 500 .

You have call ajax using get method, so first check your route file.
I think you are calling search method using post method.
Also in ajax code default is get method
you have to specify : method : post

you need to declare variable in Jquery/Javascript like below :
var value=$(this).val();
and pass this variable like below in ajax :
data:{'search':value}
Change above lines ,it should work !

Related

Laravel how to access, in a view, a value passed by a controller, but inside a script section

From a request handler I pass a parameter to a request view:
public function sol_solicitante(Request $request, $param){
return view('solicitante.solicitudes', compact('param'));
}
The view that the controller invokes is:
#extends('layouts.app')
#section('title','Buzón Solicitudes')
#section('css')
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.22/css/dataTables.bootstrap4.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.2.6/css/responsive.bootstrap4.min.css">
#endsection
#section('content')
<div class="container mt-4">
<div>
<h2>Buzón De Solicitudes</h2>
</div>
<div class="card">
<div class="card-body">
<!--
<a href="crear">
<button type="button" class="btn btn-success float-right">Crear Solicitud</button>
</a>
</h2>
-->
<table class="table table-hover" id="buzonsolicitudes">
<thead>
<tr>
<th scope="col">Id</th>
<th scope="col">Nombre</th>
<th scope="col">Estado</th>
<th scope="col"> </th>
</tr>
</thead>
</table>
</div>
</div>
</div>
#endsection
#section('js')
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.2.6/js/dataTables.responsive.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.2.6/js/responsive.bootstrap4.min.js"></script>
<script>
$('#buzonsolicitudes').DataTable({
"ajax": "{{ route('datatable.sol_solicitante',['param' => '1'])}}",
"columns":[
{data:'id'},
{data:'nombre'},
{data:'estadologico'},
{data:'btn'}
],
responsive: true,
autoWidth: false,
"language": {
"lengthMenu": "Mostrar " +
`<select class="custom-select" custom-select-sm form-control form-control-sm>
<option value='10'>10</option>
<option value='25'>25</option>
<option value='50'>50</option>
<option value='100'>100</option>
<option value='-1'>Todos</option>
</select>` +
" registros por página",
"zeroRecords": "Nada encontrado - disculpa",
"info": "Mostrando página _PAGE_ de _PAGES_",
"infoEmpty": "Ningún registro disponible",
"infoFiltered": "(filtrado de _MAX_ registros totales)",
'search':'Buscar',
'paginate':{
'next':'siguiente',
'previous':'anterior'
}
}
});
</script>
#endsection
What I don't know is how to access, in the view, the parameter sent by the controller, since I must pass it as a parameter to the Ajax call; Something like:
<script>
var p= param
$('#buzonsolicitudes').DataTable({
"ajax": "{{ route('datatable.sol_solicitante',['param' => p])}}",
This that I put does not work and checking I do not find how it should be.
I appreciate all help, thank you.
php codes are processed on server. the blade compiles all variables before page loads. look you are already using route helper. just pass the variable to the helper as you do in other places.
"ajax": "{{ route('datatable.sol_solicitante', ['param' => $param]) }}"
this will generate the route as you defined on your web.php file like mysite.com/datatable/sol_solicitante/param_value
You should create a script in blade file. In that script, you add init some variables with value from controller
Add this in your script
var data ={!! $data->id !!}; //data->id is variable send by controller
you can directly access this variable in script
Try this hope it works

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

How to call edit method of the resource controller using AJAX in Laravel5.6

In my laravel project I am using resource controller for update. but it is not working. I tried but it failed.
my blade
<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
<title>{{ config('app.name') }}</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" />
<link href="{{ asset('css/style.css') }}" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<h1>{{ config('app.name') }}</h1>
<form class="dis-none" id="FormAjax">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" />
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="address">Address</label>
<textarea class="form-control" rows="3" id="address"></textarea>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="country">Country</label>
<input type="text" class="form-control" id="country" />
</div>
</div>
</div>
<button type="submit" id="SaveAjax" class="btn btn-success">Save Form</button>
<button type="button" id="cancel" class="btn btn-danger">Cancel</button>
</form>
<div id="ShowAjax" class="row">
<button type="button" id="AddForm" class="btn btn-success">Add Form</button>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Address</th>
<th>Country</th>
<th>Action</th>
</tr>
</thead>
<tbody id="data">
</tbody>
</table>
</div>
</div>
<script type="text/javascript" src="{{ asset('js/app.js') }}"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#AddForm").click(function () {
$("#FormAjax").fadeIn();
$("#ShowAjax").hide();
$('#UpdateForm').text('Save Form');
});
$("#SaveAjax").click(function () {
$("#FormAjax").hide();
$("#ShowAjax").fadeIn();
});
$(document).on('click', '#cancel', function () {
$('#name').val('');
$('#country').val('');
$('#address').val('');
});
$(document).on('click', '#edit', function () {
$("#FormAjax").fadeIn();
$("#ShowAjax").hide();
name = $(this).parent().parent().find('#ename').text();
address = $(this).parent().parent().find('#eaddress').text();
country = $(this).parent().parent().find('#ecountry').text();
$('#name').val(name);
$('#address').val(address);
$('#country').val(country);
$('#SaveAjax').text('Edit');
$('#SaveAjax').prop('id', 'UpdateForm');
$('#UpdateForm').attr('data-id', $(this).data('id'));
});
$(document).on('click', '#UpdateForm', function () {
name = $('#name').val();
country = $('#country').val();
address = $('#address').val();
url = "peoples";
id = $(this).data('id');
editUrl = url + '/' + id + '/edit';
$.get( {{ route('editUrl') }}, {name:name, country:country, address:address, id:id}, function (data) {
console.log('success');
});
});
});
</script>
</body>
</html>
route/web.php
Route::resource('peoples', 'PeopleController');
PeopleController.php
public function edit(People $people)
{
if($request->ajax()) {
$request->validate([
'name' => 'required',
'address' => 'required',
'country' => 'required',
]);
$people = People::find($request->id);
$people->name = $request->name;
$people->address = $request->address;
$people->country = $request->country;
$people->save();
return response()->json();
}
}
When I try type in browser http://localhost:8000/peoples I see this error.
Route [editUrl] not defined. (View: C:\xampp\htdocs\Tutorials
Laravel\Ajax\resources\views\peoples.blade.php)
You cannot use the route() helper here as you have not named your routes. Instead, try using the url() helper to generate the URL.
url(id . '/edit')
But, here I see another problem as the id will come in dynamically when the JS executes by which time the Laravel helper would have already executed. So, I would suggest the following approach:
url = {{ base_url() }} + '*apiPrefix*' + '/peoples/' + id + '/edit'

Response is empty string

I am creating a simple upload files web application using laravel in the backend and I am trying to print the response that is sent from the server -which is supposed to be informed about the uploaded file- in the console, but it shows me an empty string.
here is my controller:
<?php
namespace App\Http\Controllers;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Storage;
class UploadsController extends Controller
{
public function getUpload(){
return view('upload');
}
public function postUpload(request $request){
// //
$result = print_r($request,true);
$time = Carbon::now();
if ($request->hasFile('file')) {
$file = $request->file('file');
$extension = $file->getClientOriginalExtension();
$fileName = $file->getClientOriginalName();
//$upload_success = $file->storeAs('public',$file->getClientOriginalName());
$upload_success=Storage::disk('local')->put($fileName, fopen($file, 'r+'));
if ($upload_success) {
return response()->json(['request'=>$request->getContent()], 200);
}
else {
return response()->json('error', 400);
}
}
return response()->json('no file to upload', 400);
}
}
and my view where I am printing the response:
<html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>upload</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="/js/xhr2.js"></script>
<script type="text/javascript">
$(function(){
$('#upload').on("click",function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#file").upload("/upload",function(data){
$('#spin').css('display','none');
$('#msg').css('display','block');
console.log(data);
},function(prog,val){
$('#prog').html(val+"%");
$('#prog').width(''+val+'%');
if(val == 100){
$("#prog").html('Completed');
$('#spin').css('display','block');
}
});
});
});
</script>
</head>
<body>
<div class="container">
<div style="margin-top:5px"><input type="file" id="file" name="file" ></div>
<div style="margin-top:5px;margin-bottom: 5px">
<input type="button" id="upload" value="upload" class="btn btn-success btn-lg">
</div>
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: 0%;" aria-valuemin="0" aria-valuemax="100" id="prog"></div>
</div>
<div id="spin" style="display:none">
<i class="fa fa-circle-o-notch fa-spin" style="font-size:24px"></i>
</div>
<div class="alert alert-success" style="display: none" id="msg" style="text-align: center">
<strong>Success!</strong>You have uploaded the file successfully
</div>
</div>
</body>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</html>
and here is a sample of what I get:
I would know if I am doing it wrong, and if not, why it is empty,
Thanks.
You're not using a form element.
Wrap your inputs in a basic html form:
<form method="POST" action="#">
#csrf
...
</form>
Then use jquery to post the form to the laravel route.

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

Resources