Ajax Live Search Table Generation in Laravel


In this tutorial, I will show how to make an Ajax driven live search Table in Laravel. The table will generate in real time and give results based on user input in the search box. We implement this in Laravel by using 2 view pages,  one view contains the search box and other views will display generated table. We also use some simple jquery codes in this tutorial.

Now let's start coding,

Javascript Code in livesearch.blade.php

<script>
$(document).ready(function(){
   $("#search").keyup(function(){
       var str=  $("#search").val();
       if(str == "") {
               $( "#txtHint" ).html("<b>Blogs information will be listed here...</b>"); 
       }else {
               $.get( "{{ url('demos/livesearch?id=') }}"+str, function( data ) {
                   $( "#txtHint" ).html( data );  
            });
       }
   });  
}); 
</script>

When the user types something in the search box the keyup function is triggered which in turn trigger ajax get request. The search box value is submitted to above URL as an id. The response from server is then appended to a div container.

The complete code of livesearch.blade.php (view page 1)

@extends('main')

@section('title','Ajax Live Search Table Demo -')

@section('content')

<!-- search box container starts  -->
    <div class="search">
        <h3 class="text-center title-color">Ajax Live Search Table Demo</h3>
        <p>&nbsp;</p>
        <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: rgb(124,77,255);">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 id="txtHint" class="title-color" style="padding-top:50px; text-align:center;" ><b>Blogs information will be listed here...</b></div>
     
@stop

@section('scripts')

<script>
$(document).ready(function(){
   $("#search").keyup(function(){
       var str=  $("#search").val();
       if(str == "") {
               $( "#txtHint" ).html("<b>Blogs information will be listed here...</b>"); 
       }else {
               $.get( "{{ url('demos/livesearch?id=') }}"+str, function( data ) {
                   $( "#txtHint" ).html( data );  
            });
       }
   });  
}); 
</script>

@stop

Now as said above we need to create another view page that will generate the table. This view page will be appended to div container with id txtHint when ajax is triggered by user input.

The complete code of livesearchajax.blade.php (view page 2)

<?php
if(!empty($posts ))  
{ 
    $count = 1;
    $outputhead = '';
    $outputbody = '';  
    $outputtail ='';

    $outputhead .= '<div class="table-responsive">
                    <table class="table table-bordered">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Title</th>
                                <th>Body</th>
                                <th>Created At</th>
                                <th>Options</th>
                            </tr>
                        </thead>
                        <tbody>
                ';
                  
    foreach ($posts as $post)    
    {   
    $body = substr(strip_tags($post->body),0,50)."...";
    $show = url('blog/'.$post->slug);
    $outputbody .=  ' 
                
                            <tr> 
		                        <td>'.$count++.'</td>
		                        <td>'.$post->title.'</td>
		                        <td>'.$body.'</td>
                                <td>'.$post->created_at.'</td>
                                <td><a href="'.$show.'" target="_blank" title="SHOW" ><span class="glyphicon glyphicon-list"></span></a></td>
                            </tr> 
                    ';
                
    }  

    $outputtail .= ' 
                        </tbody>
                    </table>
                </div>';
         
    echo $outputhead; 
    echo $outputbody; 
    echo $outputtail; 
 }  
 
 else  
 {  
    echo 'Data Not Found';  
 } 
 ?>  

The above view page is only used to echo the server response (Table) to the client.

The code for routes/web.php

Route::get('demos/livesearch','DemoController@liveSearch');        

The complete code of DemoController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Post;


class DemoController extends Controller
{
    public function liveSearch(Request $request)
    { 
        $search = $request->id;

        if (is_null($search))
        {
           return view('demos.livesearch');		   
        }
        else
        {
            $posts = Post::where('title','LIKE',"%{$search}%")
                           ->get();

            return view('demos.livesearchajax')->withPosts($posts);
        }
    }
}

As you can see that if search box value is null then livesearch.blade.php view page is loaded and when search box value is given then livesearchajaxdemo.blade.php view page is returned. Note I use Laravel Eloquent ORM instead of normal query builder but it is completely your choice. Also, note that both view pages are in demos folder. I use dot operator instead of slash which is also completely your choice.

The code for Post Model 

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    
}

The sample output image is given below.

Ajax Live search table laravel demo

 If you have any suggestions or doubts please comment below.

Demo

You can demo the above app by visiting the following link.


Web development
21st Jul 2018 01:21:30 PM
PHP Laravel Javascript jQuery Ajax
24391

ShareurCodes

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