Search code examples
phpdatabaselaravellaravel-5jquery-autocomplete

JQuery autocomplete with database values not working (Laravel 5)


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


Solution

  • Well unless you didn't post all of your code, your second example has several errors.

    First of all, what's $return_array and where did you get it? You are doing this $return_array[$element->id] = $element->name; unless you have declared $return_array somewhere, this will be an empty variable and you can't treat an empty variable as an array.

    Second your output it's not the same, your output is one javascript object, what you want is a array of objects. So your first example is outputting this:

    [
       {'1': 'Example1'},
       {'2': 'Example2'}
    ]
    

    And in your second example you are outputting this:

    {
        '1': 'Example1',
        '2': 'Example2'
    }
    

    One single object.

    So without knowing if you have any error besides the ones that are visible, this is how your suggestion function should be

    public function suggestion() {
    
        $term = 'programmer';
        $array = DB::table('activities')
            ->where('type', '=', 'Work')
            ->take(5)
            ->get();
    
        $return_array = [];
        foreach($array as $element) {
            //notice that we are pushing an associative array into the $return_array
            $return_array[][$element->id] = $element->name;
        }
    
        echo json_encode($return_array);
    
    }