Search code examples
phpajaxlaravelsearchbar

Implement Laravel/AJAX search bar


Hello I can do a standard AJAX/PHP search but finding it hard to convert to Laravel. I'm using key up instead of button click. I'm not sure if this is the right way im going about to implement an ajax/laravel search bar. I'm looking to output the database data into the div in the view page, but need help on going about this. If anyone thinks im doing this wrong please advise me. Always willing to learn new code.

Controller:

<?php

namespace App\Http\Controllers;

use App\Patient;

use DB;

use Illuminate\Http\Request;

class PatientController extends Controller
{


public function search(Request $request) {
    // get the search term
    $text = $request->input('text');

    // search the members table
    $patients = DB::table('patients')->where('firstname', 'Like', $text)->get();


    // return the results
    return response()->json($patients);
}

}  

Route:

Route::get('search', 'PatientController@search');

View:

   @extends('Layout.master')


@section('content')


  <!-- Ajax code -->

       <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>


    <script type="application/javascript">
    $(document).ready(function(){

        $('#txtSearch').on('keyup', function(){

            var text = $('#txtSearch').val();

            $.ajax({

                type:"GET",
                url: '127.0.0.1:8000/search',
                data: {text: $('#txtSearch').val()},
                success: function(data) {

                    console.log(data);

                 }



            });


        });

    });
    </script>

    <div style="margin-top:70px;"></div>


       @include('partials._side')

    <div class="container">

                     <form method="get" action="">

                    <div class="input-group stylish-input-group">
                        <input type="text" id="txtSearch" name="txtSearch" class="form-control"  placeholder="Search..." >
                        <span class="input-group-addon">
                            <button type="submit">
                                <span class="glyphicon glyphicon-search"></span>
                            </button>  
                        </span>
                    </div>

                     </form> 


          <div id="result"></div>

</div>

@endsection

Solution

  • In your AJAX request change:

    '127.0.0.1:8000/search'
    

    to

    '/search'
    

    I suggest you to use jQuery Autocomplete

    Very easy to set up.

    Check out the API documentation.