Laravel 5 – Autocomplete Mutiple Fields Using jQuery, Ajax and MySQL
In this post we will give you information about Laravel 5 – Autocomplete Mutiple Fields Using jQuery, Ajax and MySQL. Hear we will give you detail about Laravel 5 – Autocomplete Mutiple Fields Using jQuery, Ajax and MySQLAnd how to use it also give you demo for it if it is necessary.
Laravel 5 – Autocomplete Mutiple Fields Using jQuery, Ajax and MySQL
In this Laravel PHP Tutorial, You will learn the process of adding multiple fields with autocomplete functionality using jQuery, Ajax, Laravel and Database(MySQL).
In this example, I am going to search country using autocomplete functionality and while selecting country name from search list, the other fields will populate corresponding to search type.
Step 1: Create Sample Table
In first step, I will create sample table “countries” to test this code.
CREATE TABLE 'countries' ( 'id' int(11) NOT NULL AUTO_INCREMENT, 'sortname' varchar(3) NOT NULL, 'name' varchar(150) NOT NULL, PRIMARY KEY ('id') ) ENGINE=InnoDB AUTO_INCREMENT=247 DEFAULT CHARSET=utf8
Step 2: Add routes
In this step, I will add following two routes :
routes/web.php
- Route::get('autocomplete','AjaxAutocompleteController@index');
- Route::get('searchajax',['as'=>'searchajax','uses'=>'AjaxAutocompleteController@searchResponse']);
Route::get('autocomplete', 'AjaxAutocompleteController@index'); Route::get('searchajax', ['as'=>'searchajax','uses'=>'AjaxAutocompleteController@searchResponse']);
Using first route, We will display a form to user to search country and get the response from second routes.
Step 3: Create Controller
In this step, I will create AjaxAutocompleteController.php
in following path app/Http/Controllers.
app/Http/Controllers/AjaxAutocompleteController.php
- <?php
- namespace AppHttpControllers;
- use IlluminateHttpRequest;
- class AjaxAutocompleteController extends Controller
- {
- public functionindex(){
- returnview('autocomplete');
- }
- public functionsearchResponse(Request $request){
- $query=$request->get('term','');
- $countries=DB::table('countries');
- if($request->type=='countryname'){
- $countries->where('name','LIKE','%'.$query.'%');
- }
- if($request->type=='country_code'){
- $countries->where('sortname','LIKE','%'.$query.'%');
- }
- $countries=$countries->get();
- $data=array();
- foreach($countriesas$country){
- $data[]=array('name'=>$country->name,'sortname'=>$country->sortname);
- }
- if(count($data))
- return$data;
- else
- return['name'=>'','sortname'=>''];
- }
- }
<?php namespace AppHttpControllers; use IlluminateHttpRequest; class AjaxAutocompleteController extends Controller { public function index(){ return view('autocomplete'); } public function searchResponse(Request $request){ $query = $request->get('term',''); $countries=DB::table('countries'); if($request->type=='countryname'){ $countries->where('name','LIKE','%'.$query.'%'); } if($request->type=='country_code'){ $countries->where('sortname','LIKE','%'.$query.'%'); } $countries=$countries->get(); $data=array(); foreach ($countries as $country) { $data[]=array('name'=>$country->name,'sortname'=>$country->sortname); } if(count($data)) return $data; else return ['name'=>'','sortname'=>'']; } }
Step 4: Create View File
Now i will create a file autocomplete.blade.php
in following path resources/views/.
- <!DOCTYPEhtml>
- <html>
- <head>
- <title>Laravel 5 - Autocomplete Mutiple Fields Using jQuery, Ajax and MySQL</title>
- <linkrel="stylesheet"type="text/css"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
- <linkrel="stylesheet"type="text/css"href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css">
- <scriptsrc="http://code.jquery.com/jquery-3.2.1.min.js"></script>
- <scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
- </head>
- <body>
- <divclass="container">
- <h1>Laravel 5 - Autocomplete Mutiple Fields Using jQuery, Ajax and MySQL</h1>
- {!! Form::open() !!}
- <tableclass="table table-bordered">
- <tr>
- <th><inputclass='check_all'type='checkbox'onclick="select_all()"/></th>
- <th>S. No</th>
- <th>Country Name</th>
- <th>Country code</th>
- </tr>
- <tr>
- <td><inputtype='checkbox'class='chkbox'/></td>
- <td><spanid='sn'>1.</span></td>
- <td><inputclass="form-control autocomplete_txt"type='text'data-type="countryname"id='countryname_1'name='countryname[]'/></td>
- <td><inputclass="form-control autocomplete_txt"type='text'data-type="country_code"id='country_code_1'name='country_code[]'/></td>
- </tr>
- </table>
- <buttontype="button"class='btnbtn-dangerdelete'>- Delete</button>
- <buttontype="button"class='btnbtn-successaddbtn'>+ Add More</button>
- {!! Form::close() !!}
- </div>
- <scripttype="text/javascript">
- $(".delete").on('click', function() {
- $('.chkbox:checkbox:checked').parents("tr").remove();
- $('.check_all').prop("checked", false);
- updateSerialNo();
- });
- var i=$('table tr').length;
- $(".addbtn").on('click',function(){
- count=$('table tr').length;
- var data="<tr><td><inputtype='checkbox'class='chkbox'/></td>";
- data+="<td><spanid='sn"+i+"'>"+count+".</span></td>";
- data+="<td><inputclass='form-controlautocomplete_txt'type='text'data-type='countryname'id='countryname_"+i+"'name='countryname[]'/></td>";
- data+="<td><inputclass='form-controlautocomplete_txt'type='text'data-type='country_code'id='country_code_"+i+"'name='country_code[]'/></td></tr>";
- $('table').append(data);
- i++;
- });
- function select_all() {
- $('input[class=chkbox]:checkbox').each(function(){
- if($('input[class=check_all]:checkbox:checked').length == 0){
- $(this).prop("checked", false);
- } else {
- $(this).prop("checked", true);
- }
- });
- }
- function updateSerialNo(){
- obj=$('table tr').find('span');
- $.each( obj, function( key, value ) {
- id=value.id;
- $('#'+id).html(key+1);
- });
- }
- //autocomplete script
- $(document).on('focus','.autocomplete_txt',function(){
- type = $(this).data('type');
- if(type =='countryname' )autoType='name';
- if(type =='country_code' )autoType='sortname';
- $(this).autocomplete({
- minLength: 0,
- source: function( request, response ) {
- $.ajax({
- url: "{{ route('searchajax') }}",
- dataType: "json",
- data: {
- term : request.term,
- type : type,
- },
- success: function(data) {
- var array = $.map(data, function (item) {
- return {
- label: item[autoType],
- value: item[autoType],
- data : item
- }
- });
- response(array)
- }
- });
- },
- select: function( event, ui ) {
- var data = ui.item.data;
- id_arr = $(this).attr('id');
- id = id_arr.split("_");
- elementId = id[id.length-1];
- $('#countryname_'+elementId).val(data.name);
- $('#country_code_'+elementId).val(data.sortname);
- }
- });
- });
- </script>
- </body>
- </html>
<!DOCTYPE html> <html> <head> <title>Laravel 5 - Autocomplete Mutiple Fields Using jQuery, Ajax and MySQL</title> <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css"> <script src="http://code.jquery.com/jquery-3.2.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> </head> <body> <div > <h1>Laravel 5 - Autocomplete Mutiple Fields Using jQuery, Ajax and MySQL</h1> {!! Form::open() !!} <table > <tr> <th><input class='check_all' type='checkbox' onclick="select_all()"/></th> <th>S. No</th> <th>Country Name</th> <th>Country code</th> </tr> <tr> <td><input type='checkbox' class='chkbox'/></td> <td><span id='sn'>1.</span></td> <td><input type='text' data-type="countryname" id='countryname_1' name='countryname[]'/></td> <td><input type='text' data-type="country_code" id='country_code_1' name='country_code[]'/> </td> </tr> </table> <button type="button" class='btn btn-danger delete'>- Delete</button> <button type="button" class='btn btn-success addbtn'>+ Add More</button> {!! Form::close() !!} </div> <script type="text/javascript"> $(".delete").on('click', function() { $('.chkbox:checkbox:checked').parents("tr").remove(); $('.check_all').prop("checked", false); updateSerialNo(); }); var i=$('table tr').length; $(".addbtn").on('click',function(){ count=$('table tr').length; var data="<tr><td><input type='checkbox' class='chkbox'/></td>"; data+="<td><span id='sn"+i+"'>"+count+".</span></td>"; data+="<td><input class='form-control autocomplete_txt' type='text' data-type='countryname' id='countryname_"+i+"' name='countryname[]'/></td>"; data+="<td><input class='form-control autocomplete_txt' type='text' data-type='country_code' id='country_code_"+i+"' name='country_code[]'/></td></tr>"; $('table').append(data); i++; }); function select_all() { $('input[class=chkbox]:checkbox').each(function(){ if($('input[class=check_all]:checkbox:checked').length == 0){ $(this).prop("checked", false); } else { $(this).prop("checked", true); } }); } function updateSerialNo(){ obj=$('table tr').find('span'); $.each( obj, function( key, value ) { id=value.id; $('#'+id).html(key+1); }); } //autocomplete script $(document).on('focus','.autocomplete_txt',function(){ type = $(this).data('type'); if(type =='countryname' )autoType='name'; if(type =='country_code' )autoType='sortname'; $(this).autocomplete({ minLength: 0, source: function( request, response ) { $.ajax({ url: "{{ route('searchajax') }}", dataType: "json", data: { term : request.term, type : type, }, success: function(data) { var array = $.map(data, function (item) { return { label: item[autoType], value: item[autoType], data : item } }); response(array) } }); }, select: function( event, ui ) { var data = ui.item.data; id_arr = $(this).attr('id'); id = id_arr.split("_"); elementId = id[id.length-1]; $('#countryname_'+elementId).val(data.name); $('#country_code_'+elementId).val(data.sortname); } }); }); </script> </body> </html>
Manual Laravel Autocomplete search from Database
PHP Bootstrap – dynamic autocomplete tag input using jquery plugin
Hope this code and post will helped you for implement Laravel 5 – Autocomplete Mutiple Fields Using jQuery, Ajax and MySQL. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs