jQuery UI Autocomplete with Images and Custom HTML in Laravel


Many of us are familiar with IMDB search box which displays results in a beautiful fashion. Today I will show your how to make a live search like IMDB search box with custom images and links to the particular page and with keyboard navigation using Just a famous open source plugin called jQuery UI Autocomplete. I will show you how to customise autocomplete suggestions to look beautiful. Although this tutorial is created in Laravel anybody with basic PHP and Javascript knowledge can modify it to use in their PHP projects or Javascript projects. 

SO LET'S START CODING

1) Create Table and Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
   
}

 

2) Add Routes

Route::get('demos/autocomplete','DemoController@autoComplete');  
Route::get('demos/autocompleteajax','DemoController@autoCompleteAjax');

 

3) Create DemoController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Post;

use Helper;

class DemoController extends Controller
{
    public function autoComplete()
    {
        return view('demos.autocomplete');
    }
    
    public function autoCompleteAjax(Request $request)
    {
        $search=  $request->term;
        
        $posts = Post::where('title','LIKE',"%{$search}%")
                       ->orderBy('created_at','DESC')->limit(5)->get();

        if(!$posts->isEmpty())
        {
            foreach($posts as $post)
            {
                
                $new_row['title']= $post->title;
	            $new_row['image']= Helper::catch_first_image($post->body);
                $new_row['url']= url('blog/'.$post->slug);
                
                $row_set[] = $new_row; //build an array
            }
        }
        
        echo json_encode($row_set); 
    }
}

The autoComplete function is used to display the view page and autoCompleteAjax is called by ajax get request in view page by jQuery UI Autocomplete function. autoCompleteAjax is used to create a JSON array. The jQuery UI Autocomplete function passes a get parameter named term which contains contents of the input field. The Helper is a custom helper file created by me to load image thumbnail of each post. If you like to learn more about how to create custom helper function in laravel visit following link.

4) Create  View Page

The javascript code in the view page

 

<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet" type="text/css" media="all"/>
<script type="text/javascript">
$(document).ready(function(){
    $("#search").autocomplete({
        source: "{{ url('demos/autocompleteajax') }}",
            focus: function( event, ui ) {
            //$( "#search" ).val( ui.item.title ); // uncomment this line if you want to select value to search box  
            return false;
        },
        select: function( event, ui ) {
            window.location.href = ui.item.url;
        }
    }).data( "ui-autocomplete" )._renderItem = function( ul, item ) {
        var inner_html = '<a href="' + item.url + '" ><div class="list_item_container"><div class="image"><img src="' + item.image + '" ></div><div class="label"><h4><b>' + item.title + '</b></h4></div></div></a>';
        return $( "<li></li>" )
                .data( "item.autocomplete", item )
                .append(inner_html)
                .appendTo( ul );
    };
});
</script>  

we use _renderItem function to render our custom HTML which includes images, links and custom labels. when we select a suggestion window.location.href will assign the URL of that select to URL from our JSON array so when we press enter key or click on a particular suggestion we will be immediately redirected to the particular post page.

Now Some Custom CSS for Autocomplete

<style>
.ui-state-active h4,
.ui-state-active h4:visited {
    color: #26004d ;
}

.ui-menu-item{
    height: 80px;
    border: 1px solid #ececf9;
}
.ui-widget-content .ui-state-active {
    background-color: white !important;
    border: none !important;
}
.list_item_container {
    width:740px;
    height: 80px;
    float: left;
    margin-left: 20px;
}
.ui-widget-content .ui-state-active .list_item_container {
    background-color: #f5f5f5;
}

.image {
    width: 15%;
    float: left;
    padding: 10px;
}
.image img{
    width: 80px;
    height : 60px;
}
.label{
    width: 85%;
    float:right;
    white-space: nowrap;
    overflow: hidden;
    color: rgb(124,77,255);
    text-align: left;
}
input:focus{
    background-color: #f5f5f5;
}

</style>

You can adjust the height and width and background colour by modifying above CSS codes.

The Complete View Page

@extends('main')

@section('title','jQuery UI Autocomplete with Images Demo -')

@section('stylesheets')

<!-- Refer CSS Codes given above -->

@endsection

@section('content')

<!-- search box container starts  -->
<h3 class="text-center title-color"><u>jQuery UI Autocomplete with Images Demo</u></h3>
    <p>&nbsp;</p>
    <div class="well">
        <div class="row">
            <div class="col-lg-10 col-lg-offset-1">
                <div class="input-group">
                    <span class="input-group-addon" style="color: white; background-color: #5b518b">BLOG SEARCH</span>
                    <input type="text" autocomplete="off" id="search" class="form-control input-lg" placeholder="Enter Blog Title Here">
                </div>
            </div>
        </div>
    </div>
<!-- search box container ends  -->
<div style="padding-top:280px;" ></div>
    
@stop

@section('scripts')

<!-- Refer Javasript Codes given above -->  
    
@stop

The sample image of above code is given below.

jQuey UI Autocomplete with Image Demo - ShareurCodesThe Demo

You can demo the following application by visiting the following link.

https://shareurcodes.com/demos/autocomplete

If you have any suggestions or doubts please comment below and I try will respond to every one of you as early as possible.


Web development
21st Jul 2018 01:14:17 PM
PHP Laravel Javascript jQuery HTML & CSS
21470

ShareurCodes

ShareurCodes is a code sharing site for programmers to learn, share their knowledge with younger generation.