Diego Cespedes Diego Cespedes - 1 month ago 14
jQuery Question

Laravel 5.2 - Autocomplete dropdown with jquery

I'm tryng to code an autocomplete suggest input extracting a list from my database. I have a list of municipalities, but it doesn't work.

I tried like this:

ROUTES

Route::get('/crea-regalo', 'PostController@form');
Route::post('/crea-regalo', 'PostController@creaPost');
Route::get('/', 'HomeController@index');
Route::get('getdata', 'PostController@getData');


CONTROLLER

public function getData(Request $request) {

$termn = $request->termn;

// controllo
$data = Municipality::where('name', 'LIKE', '%'.$termn.'%')
->take(10)
->get();
$results = array();

foreach ($data as $key => $v) {
$results[]=['id' => $v->id, 'value' => $v->name];
}

return response()->json($results);
}


VIEW - FORM SECTION

<!-- Select Basic -->
<div class="form-group">
<label class="col-md-3 control-label" for="seller-Location">Municipality</label>
<div class="col-md-8">
<input type="text" name="municipality" placeholder="comune" id="searchname">
</div>
</div>


JS

$('#searchname').autocomplete({
minLength: 1,
autoFocus: true,
source: '{{!!URL::route('getdata')!!}}',
select: function(e, ui){ alter(ui);},
});


My console shows me an error like this:


Uncaught SyntaxError: Unexpected identifier line 10 of my js file:
source: '{{!!URL::route('getdata')!!}}',

Answer

{{!! !!}} isn't valid you could use {{ }} or {!! !!} instead.

Try to not mix JS with PHP code, and add a hidden input in your blade :

<input type="hidden" id="route-url" value="{{ route('getdata') }}">
//Or
<input type="hidden" id="route-url" value="{{ URL::route('getdata') }}">

JS :

$('#searchname').autocomplete({
    minLength: 1,
    autoFocus: true,
    source: $('#route-url').val(),
    select: function(e, ui){ alter(ui);},
});

Hope this helps.

Comments