简体   繁体   中英

PHP Laravel : Autocomplete Search 404 (Not Found)

I'm building a laravel application where I have to use autocomplete search in my application.

My Route:

Route::get('/autocomplete',[
        'uses'=>'CourseController@autocomplete',
        'as'=>'autocomplete'
        ]); 

My Controller:

 public function autocomplete(Request $request)
    {

        $item = $request->input(['searchname']);
        $results=array();
        $queries = DB::table('courses')
        ->where('name', 'LIKE', '%'.$term.'%')  
        ->take(5)->get();

        foreach ($queries as $data) {
          $results[]=['id'=>$data->id,'value'=>$data->name];
        }
    return Response::json($results);
    }

My View Page:

 {{ Form::open(['action' => ['UserController@autocomplete'], 'method' => 'GET']) }}
    {{ Form::text('searchname', '', ['id' =>  'searchname', 'placeholder' =>  'Enter name'])}}
    {{ Form::submit('Search', array('class' => 'button expand')) }}
{{ Form::close() }}


    <script type="text/javascript">
    jQuery(document).ready(function($) {
      $('#searchname').autocomplete({
            source:  "/autocomplete" ,
            minlength:1,
            autofocus:true,
            select:function(event,ui){
              $("searchname").val(ui.item.value);
            }
      });
      });
    </script>

So when I search for a item instead of getting item name i'm getting following Error in my console:

GET http://localhost/autocomplete?term=tree 404 (Not Found)

Anyone who can help me to find the solution please?

The source for your autocomplete is the problem. You are passing a path relative to your server document root, rather than a route within your site. Also, you don't need the form, since the search is done asynchronously.

You can try this

<input type="text" id="searchname" placeholder="Enter name"/>

and

<script type="text/javascript">
  jQuery(document).ready(function($) {
     $('#searchname').autocomplete({
        source: "{{ route('autocomplete') }}" ,
        minlength:1,
        autofocus:true,
        select:function(event,ui){
          $("searchname").val(ui.item.value);
        }
     });
  });
</script>

EDIT: I'm assuming the root of your site is at http://localhost/your-site and not just localhost . Also, in your Routes you are using CourseController then in the form you write UserController . Since you are naming the route anyway it would be good to use the route helper to generate the correct URL.


Finally, in your controller you should get the input of name "term", not "searchname".

$term = $request->term;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM