I'm trying to get data for autocomplete using laravel.
Controller:
public function collection_search(Request $request) {
$term = $request->search;
$serveurapObj = new Serveurap();
$result = $serveurapObj->collectionAutocomplete();
return response()->json($result);
}
Model:
public function collectionAutocomplete($term) {
$where= ['m.supprime'=>'0', 's.supprime'=>'0'];
return DB::table('serveuraps AS s')
->select(DB::raw('s.nom as hostname'))
->join('machines AS m','m.id','=','s.machine_id')
->join('typeserveurs AS t','t.id','=','m.typeserveur_id')
->where($where)
->where('hostname','like','%'.$term.'%')
->get();
}
View:
<div >
<div >
<label >{!! __('script.serveur') !!}</label>
<div >
<input type="text" name="serveur" id="relance-serveur" role="textbox" aria-autocomplete="list" aria-haspopup="true">
</div>
</div>
</div>
Jquery/Ajax:
$(document).ready(function () {
// relance serveur autocomplete textbox
$('#relance-serveur').autocomplete({
source: function (request, response) {
alert(request.term)
$.ajax({
url: '/scripts/relanceCollection/collection',
dataType: 'json',
data: {
search: request.term
},
success: function (data) {
response(data);
}
});
},
});
});
I'm getting error when accessing the search
from js in controller.
Error:
I printed $request
but it showed the json data from model. how would I get the search
from js to controller so that I can search data based on that term ?
CodePudding user response:
The key you are sending is search
, not term
. Either change your controller code to reflect that, or change the ajax data.
$.ajax({
...
data: {
→ search: request.term
},
...
});
public function collection_search(Request $request)
{
$term = $request->search; ←
...
}
$.ajax({
...
data: {
→ term: request.term
},
...
});
public function collection_search(Request $request)
{
$term = $request->term; ←
...
}
CodePudding user response:
You aliased the wrong class. You don't want an instance of a Facade, ever. If you want an instance of something you want the underlying instance, not the facade.
use Illuminate\Http\Request;
Now, $request
would be an instance of that class and not the Facade, Illuminate\Support\Facades\Request
.