article

Thursday, July 7, 2022

Laravel 9 Autocomplete Textbox with JQuery Ajax

Laravel 9 Autocomplete Textbox with JQuery Ajax

How to install laravel 9

https://tutorial101.blogspot.com/2022/02/how-to-install-laravel-9.html

Connecting our Database

open .env file root directory.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laraveldb
DB_USERNAME=root
DB_PASSWORD=

Create tables 

php artisan make:migration create_countries_table
C:\xampp\htdocs\laravel\laravelproject>php artisan make:migration create_countries_table


Open new migrations
yourproject/database/migrations
laravelproject\database\migrations\create_countries_table.php

laravelproject\database\migrations\create_countries_table.php
	
//laravelproject\database\migrations\create_countries_table.php			
<?php
return new class extends Migration
{
    public function up()
    {
        Schema::create('countries', function (Blueprint $table) {
            $table->id();
            $table->string('country_code');
            $table->string('country_name');
            $table->timestamps();
        });
    }
};
Database Migration
php artisan migrate

C:\xampp\htdocs\laravel\laravelproject>php artisan migrate
Migration table created successfully.
check database table

Create tables Model

php artisan make:model Countries
Creating Controller

php artisan make:controller AutocompleteController
C:\xampp\htdocs\laravel\laravelproject>php artisan make:controller AutocompleteController
change it with the following codes:
laravelproject\app\Http\Controllers\AutocompleteController.php
//laravelproject\app\Http\Controllers\AutocompleteController.ph
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class AutocompleteController extends Controller
{
    function index()
    {
        return view('autocomplete');
    }

    function fetch(Request $request)
    {
        if($request->get('query'))
        {
            $query = $request->get('query');
            $data = DB::table('countries')
                ->where('country_name', 'LIKE', "%{$query}%")
                ->get();
            $output = '<ul class="dropdown-menu" style="display:block; position:relative;width:100%;">';
            foreach($data as $row)
            {
                $output .= '
                <li><a class="dropdown-item" href="#">'.$row->country_name.'</a></li>
                ';
            }
            $output .= '</ul>';
            echo $output;
        }
    }
}
Route
laravelproject\routes\web.php
//laravelproject\routes\web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AutocompleteController; //add DepartmentsController

Route::get('/', function () {
    return view('welcome');
});
  
Route::get('/autocomplete', [AutocompleteController::class, 'index']);
Route::post('/autocomplete/fetch', [AutocompleteController::class, 'fetch'])->name('autocomplete.fetch');
Create Views
laravelproject\resources\views\autocomplete.blade.phpp

Bootstrap 5 https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js
//laravelproject\resources\views\autocomplete.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 9 Autocomplete Textbox with JQuery Ajax</title>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
<style type="text/css">
   .box{
    width:600px;
    margin:0 auto;
   }
</style>
</head>
<body>
<p style="padding:20px;"><h3 align="center">Laravel 9 Autocomplete Textbox with JQuery Ajax</h3></p>
<div class="container box">
   <div class="form-group">
        <input type="text" name="country_name" id="country_name" class="form-control" placeholder="Enter Country Name" />
        <div id="countryList"></div>
   </div>
   {{ csrf_field() }}
</div>
<script>
$(document).ready(function(){

    $('#country_name').keyup(function(){ 
        var query = $(this).val(); 
        if(query != '')
        {
            var _token = $('input[name="_token"]').val();
            $.ajax({
                url:"{{ route('autocomplete.fetch') }}",
                method:"POST",
                data:{query:query, _token:_token},
                success:function(data){
                $('#countryList').fadeIn();  
                    $('#countryList').html(data);
                }
            });
        }
    });

    $(document).on('click', 'li', function(){  
        $('#country_name').val($(this).text());  
        $('#countryList').fadeOut();  
    });  

});
</script>
</body>
</html>
Run C:\xampp\htdocs\laravel\laravelproject>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

Related Post