This is (part of) my view, generated by Laravel Forms:
<form method="POST" action="http://laravelapp/search" accept-charset="UTF-8">
<input name="_token" type="hidden" value="g3RA...">
<input type="text" placeholder="Search" id="terms">
</form>
<script>
$( function() {
var testdata = [ "ActionScript", "AppleScript", "JavaScript" ];
$( "#terms" ).autocomplete({
minLength: 1,
source: '{{ URL::route('index.search') }}'
//source: testdata
});
});
</script>
These is the route for index.search
:
Route::post('/search', 'IndexController@search')->name('index.search');
This is my IndexController
:
public function search(Request $request)
{
return Response('Hello World');
}
For the sake of simplicity, I replaced the actual search algorithm with a static response Hello World
. However, the autocomplete works fine if I uncomment the //source: testdata
line in the javascript code. When I use the route to the IndexController, nothing happens.
When I press enter (=submit the form), a new page is loaded with Hello World
, but there's no dynamic search result.
As you can see, I inserted the CSRF token and the search()
method returns a valid response. However, it is not triggered by the javascript. My questions, thus, are:
- What's wrong with my code?
- Should the route be GET or POST?
- Should there be a form around the input field? Usual jQuery demo examples don't have it, but it's probably needed for the CSRF protection.
Any help is greatly appreciated!