Laravel 5 – Autocomplete Mutiple Fields Using jQuery, Ajax and MySQL

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

  1. Route::get('autocomplete','AjaxAutocompleteController@index');
  2. 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

  1. <?php
  2. namespace AppHttpControllers;
  3. use IlluminateHttpRequest;
  4. class AjaxAutocompleteController extends Controller
  5. {
  6.     public functionindex(){        
  7.         returnview('autocomplete');
  8.     }
  9.     public functionsearchResponse(Request $request){
  10.         $query=$request->get('term','');
  11. $countries=DB::table('countries');
  12. if($request->type=='countryname'){
  13.     $countries->where('name','LIKE','%'.$query.'%');
  14. }
  15. if($request->type=='country_code'){
  16.             $countries->where('sortname','LIKE','%'.$query.'%');
  17. }
  18.     $countries=$countries->get();
  19. $data=array();
  20. foreach($countriesas$country){
  21. $data[]=array('name'=>$country->name,'sortname'=>$country->sortname);
  22. }
  23. if(count($data))
  24. return$data;
  25. else
  26. return['name'=>'','sortname'=>''];
  27.     }
  28. }
<?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/.

  1. <!DOCTYPEhtml>
  2. <html>
  3. <head>
  4.     <title>Laravel 5 - Autocomplete Mutiple Fields Using jQuery, Ajax and MySQL</title>
  5.     <linkrel="stylesheet"type="text/css"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  6. <linkrel="stylesheet"type="text/css"href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css">
  7.     <scriptsrc="http://code.jquery.com/jquery-3.2.1.min.js"></script>
  8. <scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
  9. </head>
  10. <body>
  11. <divclass="container">
  12. <h1>Laravel 5 - Autocomplete Mutiple Fields Using jQuery, Ajax and MySQL</h1>
  13. {!! Form::open() !!}
  14.     
  15. <tableclass="table table-bordered">
  16. <tr>
  17. <th><inputclass='check_all'type='checkbox'onclick="select_all()"/></th>
  18. <th>S. No</th>
  19. <th>Country Name</th>
  20. <th>Country code</th>
  21. </tr>
  22. <tr>
  23. <td><inputtype='checkbox'class='chkbox'/></td>
  24. <td><spanid='sn'>1.</span></td>
  25. <td><inputclass="form-control autocomplete_txt"type='text'data-type="countryname"id='countryname_1'name='countryname[]'/></td>
  26. <td><inputclass="form-control autocomplete_txt"type='text'data-type="country_code"id='country_code_1'name='country_code[]'/></td>
  27. </tr>
  28. </table>
  29. <buttontype="button"class='btnbtn-dangerdelete'>- Delete</button>
  30. <buttontype="button"class='btnbtn-successaddbtn'>+ Add More</button>
  31. {!! Form::close() !!}
  32. </div>
  33. <scripttype="text/javascript">
  34. $(".delete").on('click', function() {
  35. $('.chkbox:checkbox:checked').parents("tr").remove();
  36. $('.check_all').prop("checked", false);
  37. updateSerialNo();
  38. });
  39. var i=$('table tr').length;
  40. $(".addbtn").on('click',function(){
  41. count=$('table tr').length;
  42. var data="<tr><td><inputtype='checkbox'class='chkbox'/></td>";
  43. data+="<td><spanid='sn"+i+"'>"+count+".</span></td>";
  44. data+="<td><inputclass='form-controlautocomplete_txt'type='text'data-type='countryname'id='countryname_"+i+"'name='countryname[]'/></td>";
  45. data+="<td><inputclass='form-controlautocomplete_txt'type='text'data-type='country_code'id='country_code_"+i+"'name='country_code[]'/></td></tr>";
  46. $('table').append(data);
  47. i++;
  48. });
  49. function select_all() {
  50. $('input[class=chkbox]:checkbox').each(function(){
  51. if($('input[class=check_all]:checkbox:checked').length == 0){
  52. $(this).prop("checked", false);
  53. } else {
  54. $(this).prop("checked", true);
  55. }
  56. });
  57. }
  58. function updateSerialNo(){
  59. obj=$('table tr').find('span');
  60. $.each( obj, function( key, value ) {
  61. id=value.id;
  62. $('#'+id).html(key+1);
  63. });
  64. }
  65. //autocomplete script
  66. $(document).on('focus','.autocomplete_txt',function(){
  67. type = $(this).data('type');
  68. if(type =='countryname' )autoType='name';
  69. if(type =='country_code' )autoType='sortname';
  70. $(this).autocomplete({
  71. minLength: 0,
  72. source: function( request, response ) {
  73. $.ajax({
  74. url: "{{ route('searchajax') }}",
  75. dataType: "json",
  76. data: {
  77. term : request.term,
  78. type : type,
  79. },
  80. success: function(data) {
  81. var array = $.map(data, function (item) {
  82. return {
  83. label: item[autoType],
  84. value: item[autoType],
  85. data : item
  86. }
  87. });
  88. response(array)
  89. }
  90. });
  91. },
  92. select: function( event, ui ) {
  93. var data = ui.item.data;
  94. id_arr = $(this).attr('id');
  95. id = id_arr.split("_");
  96. elementId = id[id.length-1];
  97. $('#countryname_'+elementId).val(data.name);
  98. $('#country_code_'+elementId).val(data.sortname);
  99. }
  100. });
  101. });
  102. </script>
  103. </body>
  104. </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

Show Demo

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

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

1  +  1  =  

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US