简体   繁体   中英

Autocomplete Search not Working in Laravel

I have a search field with the same name and id inside my categories page and inside my products page.The autocomplete suggestions seems to work fine , however once I click on requested product inside the search field, it's stays on the same page and not redirecting me to the view.I want my view to show only products. This is my code so far:

After update

My routes:

<?php

Route::get('products/{id}', 'AutoCompleteController@show');
Route::get('autocomplete', array('as' => 'autocomplete', 'uses' => 'AutoCompleteController@show'));
Route::get('searchajax', array('as' => 'searchajax', 'uses' => 'AutoCompleteController@autoComplete')); 

My AutoCompleteController:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\MainController;
use App\Product;

class AutoCompleteController extends MainController
{
    public function show(Product $product)
    {
        return view('content.products', ['product' => $product]);
    }

    public function autoComplete(Request $request)
    {
        $query = $request->get('term', '');

        $products = Product::where('title', 'LIKE', '%' . $query . '%')->get();

        $data = [];
        foreach ($products as $product) {
            $data[] = array('label' => $product->title, 'value' => $product->id);
        }
        if (count($data)) {
            return $data;
        } else {
            return ['value' => 'No Result Found', 'id' => ''];
        }
    }
}

My view in products.blade.php and categories.blade.php for my autocomplete search is the same:

@extends('master')
@section('content')
    <link href="http://demo.expertphp.in/css/jquery.ui.autocomplete.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    <div class="row">
        <form class="navbar-form text-center " form method="GET" action=" ">
            <input id="search_text" placeholder=" Search products" name="search_text" type="text" value=""
                   style="width: 400px; height: 35px; border-radius: 5px ; padding-left: 12px;"><br><br>
            <input class="btn btn-default " type="submit" value="  Search">
        </form>
    </div>

    <script>
        $(document).ready(function () {
            src = "{{ route('searchajax') }}";
            $("#search_text").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: src,
                        dataType: "json",
                        data: {
                            term: request.term
                        },
                        success: function (data) {
                            response(data);
                        }
                    });
                },
                minLength: 3,
                select: function (event, ui) {
                    window.location = '{{ url('shop/{category_url}')}}' + ui.item.id
                } // not sure if this is the correct way , please advise
            });
        });
    </script>
@endsection

If you seems the issue with JS conflict, try below code:

<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

Added missing ui css too. Let me know the result.

There are a few problems:

  • An autocomplete response should include label and value pairs, you are returning value and id . See the jQuery UI source docs .

  • Your Javascript is missing the select event handler, which specifies what happens when one of the suggestions is selected. So right now clicking one will just fill the clicked value in the input field. See the jQueryUI autocomplete select docs .

Maybe you want to be able to view product ID 1 when you browse to /products/1 . First you need to set up a route for that:

Route::get('products/{id}', 'AutoCompleteController@index');

Then in your controller, first fix the autocomplete response to return the right format:

foreach ($products as $product) {
    $data[]=array('label'=>$product->title,'value'=>$product->id);
}

Next, still in the controller, update the method for showing your product (BTW this should probably be called show , index would usually be a list of products:

use App\Product;

class AutoCompleteController extends MainController {

    // This assumes you have a Product model
    public function index(Product $product) {
        return view('content.products', ['product' => $product]);
    }

And your Javascript:

$("#search_text").autocomplete({
    source: function (request, response) {
        $.ajax({
            url: src,
            dataType: "json",
            data: {
                term: request.term
            },
            success: function (data) {
                response(data);

            }
        });
    },
    minLength: 3,
    select: function( event, ui ) {
        // Your autoComplete response returns the ID in the 'value' field
        window.location = 'http://yoursite.com/products/' + ui.item.value
    }
});

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