Ajax Автозаполнение не работает должным образом в Laravel 6 - PullRequest
0 голосов
/ 18 февраля 2020

Я видел учебник по AJAX Автозаполнение выглядит нормально, но проблема в том, что он также отображает все данные, а не те, которые я ищу.

enter image description here

Извините, я новичок в ajax Можете ли вы помочь мне исправить это?

от моего контроллера

public function search(Request $request){
    // check if ajax request is coming or not
    if($request->ajax()) {
        // select country name from database
        $data = Vendor::where('vendor_id', 'LIKE', '%'.$request->vendor_id.'%')
            ->get();
        // declare an empty array for output
        $output = '';
        // if searched countries count is larager than zero
        if (count($data)>0) {
            // concatenate output to the array
            $output = '<ul class="list-group" style="display: block; position: relative; z-index: 1">';
            // loop through the result array
            foreach ($data as $row){
                // concatenate output to the array
                $output .= '<li class="list-group-item">'.$row->vendor_id. ' ' .$row->vendor_name.'</li>';
            }
            // end of output
            $output .= '</ul>';
        }
        else {
            // if there's no matching results according to the input
            $output .= '<li class="list-group-item">'.'No results'.'</li>';
        }
        // return output result array
        return $output;
    }
}

My Blade

    <div class="row">
        <div class="col-lg-12"></div>
        <div class="col-lg-6">
            <div class="form-group">
                <input type="text" name="vendor_id" id="vendor_id" data-type="vendor_id" placeholder="Enter vendor ID" class="form-control autocomplete_txt">
                {{-- <input class="typeahead form-control" type="text"> --}}
            </div>
            <div id="vendor_list"></div>
        </div>
        <div class="col-lg-6">
            <div class="form-group">
                <input type="text" name="vendor_name" id="vendor_name" placeholder="Vendor Name" class="form-control" readonly="true">
            </div>                    
        </div>                
        <div class="col-lg-12"></div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
    <script type="text/javascript">
        // jQuery wait till the page is fullt loaded
        $(document).ready(function () {
            // keyup function looks at the keys typed on the search box
            $('#vendor_id').on('keyup',function() {
                // the text typed in the input field is assigned to a variable 
                var query = $(this).val();
                // call to an ajax function
                $.ajax({
                    // assign a controller function to perform search action - route name is search
                    url:"{{ route('admin.search') }}",
                    // since we are getting data methos is assigned as GET
                    type:"GET",
                    // data are sent the server
                    data:{'vendor':query},
                    // if search is succcessfully done, this callback function is called
                    success:function (data) {
                        // print the search results in the div called vendor_list(id)
                        $('#vendor_list').html(data);
                    }
                })
                // end of ajax call
            });

            // initiate a click function on each search result
            $(document).on('click', 'li', function(){
                // declare the value in the input field to a variable
                var value = $(this).text();
                // assign the value to the search box
                $('#vendor_id').val(value);
                // after click is done, search results segment is made empty
                $('#vendor_list').html("");
            });
        });
    </script>

Маршрут

Route::get('search', 'PurchasedOrderController@search')->name('search');

Можете ли вы помочь мне исправить выпадающий список, а также отобразить имя поставщика в поле ввода имени поставщика после срабатывания кода клика? Заранее большое спасибо !!!

enter image description here

1 Ответ

2 голосов
/ 18 февраля 2020

Для меня ваша проблема исходит от вашего контроллера, и вам также нужен почтовый запрос или оставайтесь в получении и делайте так.

Контроллер

public function search(Request $request, $vendor){
// check if ajax request is coming or not
if($request->ajax()) {
    // select country name from database
    $data = Vendor::where('vendor_id', 'LIKE', '%'.$vendor.'%')
        ->get();
    // declare an empty array for output
    $output = '';
    // if searched countries count is larager than zero
    if (count($data)>0) {
        // concatenate output to the array
        $output = '<ul class="list-group" style="display: block; position: relative; z-index: 1">';
        // loop through the result array
        foreach ($data as $row){
            // concatenate output to the array
            $output .= '<li class="list-group-item">'.$row->vendor_id. ' ' .$row->vendor_name.'</li>';
        }
        // end of output
        $output .= '</ul>';
    }
    else {
        // if there's no matching results according to the input
        $output .= '<li class="list-group-item">'.'No results'.'</li>';
    }
    // return output result array
    return $output;
}}

Ваш маршрут

Route::get('search/{vendor}', 'PurchasedOrderController@search')->name('search');

Ваш клинок

    $(document).ready(function () {
        // keyup function looks at the keys typed on the search box
        $('#vendor_id').on('keyup',function() {
            // the text typed in the input field is assigned to a variable 
            var query = $(this).val();
            // call to an ajax function
            $.ajax({
                url:"yourdomain.com/search/"+query,
                // since we are getting data methos is assigned as GET
                type:"GET",
                // if search is succcessfully done, this callback function is called
                success:function (data) {
                    // print the search results in the div called vendor_list(id)
                    $('#vendor_list').html(data);
                }
            })
            // end of ajax call
        });

Это должно работать, также не в посте вы должны изменить в контроллере свой $request->vendor_id это не хорошо, изменить на $request->vendor и пройти свой маршрут laravel и ajax запрос в посте, и он должен работать

для onclick:

$('#list-group-item').on('click', function(){

    var item_select = $(this).text();
    $('#vendor_id').val(item_select);
    $('#vendor_list').html("");
 });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...