arrigonfr arrigonfr - 4 months ago 21
PHP Question

Laravel 4.1 AutoComplete Field not showing results

Ok, so here's the exact problem that i'm having. I have this autocomplete field and whenever I type anything in it, my console shows me every single record in the table i get my results from, no matter what I type.
Below the field, a list of "results" comes up blank, no text in any of the options.
Here's my code.

The AutoComplete Field

{{ Form::text('busqueda', '', array('class'=>'ui-widget ui-widget-content ui-corner-all', 'id'=>'busqueda')) }}


The jQuery

$(document).ready(function(){
$("#busqueda").autocomplete({
source: function (request, response) {
$.ajax({
url: "{{URL('ajax/getBooksAutocomplete')}}",
data: {
busqueda: this.term
},
success: function (data) {
// data must be an array containing 0 or more items
console.log("[SUCCESS] " + data.length + " item(s)");
//response(data);
response( $.map( data, function( item ) {
return {
label: item.name,
value: item.id
};
}));
},
});
},
});
});


The Route

Route::get('ajax/getBooksAutocomplete', array('uses'=>'BookController@getBooksAutocomplete'));


The Controller

class BookController extends BaseController {
...
public function getBooksAutocomplete(){
$term = Input::get('busqueda');
$books = array();
$search = DB::table('books')->where('name', 'LIKE', '%'.$term.'%')->get();
foreach($search as $results => $book){
$books[] = array('id'=>$book->id, 'name'=>$book->name);
}
return Response::json($books);
}
...
}


Any help provided will be appreciated.

Answer

have you tried using id, label, value as default array key?

class BookController extends BaseController {
...
    public function getBooksAutocomplete(){
        $term = Input::get('busqueda');
        $books = array();
        $search = DB::table('books')->where('name', 'LIKE', '%'.$term.'%')->get();
        foreach($search as $results => $book){
            $books[] = array('id'=>$book->id, 'label'=>$book->name, 'value'=>$book->id);
        }
        return Response::json($books);
    }
...
}

this should let you use autocomplete with less code at the javascript side.

make the busqueda a hidden field to save the selected autocomplete option and buesqueda2 as the autocomplete. so when you select busqueda2, it will update the hidden input buesqueda with the selected option. so to do this, you add this to the javascript side:

 $("#busqueda2").autocomplete({
  ....
   select: function (event, ui) {
    $('#busqueda2').val(ui.item.label);
    $('#busqueda').val(ui.item.id);
   }
  ....
});
Comments