I am currently facing issues with an ajax search, I think it has to do with the routes, but I’m not sure what is wrong. Maybe it’s too early for coding.
This works
<script type="text/javascript">
$('#name').on('keyup',function(){
$value=$(this).val();
$.ajax({
type : 'get',
url : '{{ URL::to("/search") }}',
data:{'name':$value},
success:function(data){
$('tbody').html(data);
}
});
})
</script>
This does not work
<script type="text/javascript">
$('#name').on('keyup',function(){
$value=$(this).val();
$.ajax({
type : 'get',
url : '{{ URL::to("/associates/search") }}', // Does not change if route name is used
data:{'name':$value},
success:function(data){
$('tbody').html(data);
}
});
})
</script>
The routes are the following
Route::resource('associates', 'AssociateController');
Route::get('/search','AssociateController@search');
Route::get('/associates/search', 'AssociateController@search')->name('associate.search');
The search method in the controller
public function search(Request $request)
{
if($request->ajax())
{
$output="";
$associates=DB::table('associates')->where('name','LIKE','%'.$request->name.'%')->limit(10)->get();
if($associates)
{
foreach ($associates as $key => $associate) {
$output.='<tr>'.
'<td>'.$associate->id.'</td>'.
'<td>'.$associate->name.'</td>'.
'</tr>';
}
return Response($output);
}
}
}
2
Answers
If you’re already using named routes
->name('associate.search')
, try to get the route URL by its name:Why?
Because you created a resource route with URI
associates
:This resource is reserved for :
That’s why
/associates/search
conflict with that resource URI.How to solve?
You need , just add a route to that method separately, before you register the resource: