php - JQuery autocomplete with database values not working (Laravel 5) -


goal: show suggestions in form's text box based on data 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 expected

public function suggestion() {      $return_array = array('1' => 'example1',         '2' => 'example2');      echo json_encode($return_array);  } 

code 2: values database, doesn't work:

public function suggestion() {      $term = 'programming';     $array = db::table('activities')         ->where('type', '=', 'work')         ->take(5)         ->get();       foreach($array $element) {         $return_array[$element->id] = $element->name;     }      echo json_encode($return_array);  } 

error: internal server error 500

i decided echo $return_array code 2 in separate controller , ouput following:

{'1': 'example1', '2': 'example2' } 

which same thing (i think) works hardcoded in code 1.

why code 1 work while code 2 doesn't? what's difference? in advance

well unless didn't post of code, second example has several errors.

first of all, what's $return_array , did it? doing $return_array[$element->id] = $element->name; unless have declared $return_array somewhere, empty variable , can't treat empty variable array.

second output it's not same, output 1 javascript object, want array of objects. first example outputting this:

[    {'1': 'example1'},    {'2': 'example2'} ] 

and in second example outputting this:

{     '1': 'example1',     '2': 'example2' } 

one single object.

so without knowing if have error besides ones visible, how suggestion function should be

public function suggestion() {      $term = 'programmer';     $array = db::table('activities')         ->where('type', '=', 'work')         ->take(5)         ->get();      $return_array = [];     foreach($array $element) {         //notice pushing associative array $return_array         $return_array[][$element->id] = $element->name;     }      echo json_encode($return_array);  } 

Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -