Goal: Show suggestions in a form's text box based on data from database
<script>
$(function() {
$( "#activitynamebox" ).autocomplete({
source: '{{URL('getactivitydata')}}',
minlength: 1, //search after 1 character
select:function(event,ui){
$('#response').val(ui.item.value);
}
});
});
</script>
The problem
code 1: works as expected
public function suggestion() {
$return_array = array('1' => 'Example1',
'2' => 'Example2');
echo json_encode($return_array);
}
code 2: with values from database, doesn't work:
public function suggestion() {
$term = 'programming';
$array = DB::table('activities')
->where('type', '=', 'Work')
->take(5)
->get();
foreach($array as $element) {
$return_array[$element->id] = $element->name;
}
echo json_encode($return_array);
}
Error: Internal Server Error 500
I decided to echo $return_array from code 2 in a separate controller and the ouput was the following:
{'1': 'Example1', '2': 'Example2' }
Which is the same thing (I think) that works hardcoded in code 1.
Why does code 1 work while code 2 doesn't? What's the difference? Thanks in advance