Autocomplete text field in laravel using database

醉酒当歌 提交于 2019-12-09 13:30:08

问题


I am trying to make a autocomplete form like below but the form do not show the suggestion as my database query is ok.

Form cole:

Controller method code:

Routes:

When I search on the link I get the query result like this:

Shows the result:

[{"id":1,"value":"sourav hossen"},{"id":2,"value":"sourav hossen"},{"id":3,"value":"sourav hossen"},{"id":4,"value":"a b"},{"id":5,"value":"a a"}]


回答1:


Try this change, some time will work.

source: "{{URL::route('autocomplete')}}",



回答2:


I tried to do it with jquery ajax and it worked.
First of all you should include a jquery library before the following code.

The javascript code in your view should be:

<script>
$(document).ready(function(){
    $('#q').keyup(function () {
        var q=$(this).val();
        if(word.length>3) {

            $.ajax
            ({
                type: "GET",
                url: "test2",
                data: {q:q},
                contentType: "json",
                cache: false,
                success: function(data, status, xhr)
                {
                    $('#q').val(data[0].value);
                }
            });
        }
    });

});
</script>

In your controller you should get the ajax data

public function autocomplete(Request $request)
{
    $input = $request->all();
    $term = $input['q'];
    $result = array();
    $queries = ...(do whatever you like)

                ->take(5)->get();
    foreach($queries as $query)
    {
        $result[] = ['id'=> $query->id,'value'=>$query->firstname.' '.$query->lastname];
    }

    return response()->json($result);

}

Try this and if you find any difficulty, i'll be here.



来源:https://stackoverflow.com/questions/28059433/autocomplete-text-field-in-laravel-using-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!