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

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

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']);

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 App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. class AjaxAutocompleteController extends Controller
  5. {
  6.     public function index(){        
  7.         return view('autocomplete');
  8.     }
  9.     public function searchResponse(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 ($countries as $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. }
Step 4: Create View File

Now i will create a file autocomplete.blade.php in following path resources/views/.

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.     <title>Laravel 5 - Autocomplete Mutiple Fields Using jQuery, Ajax and MySQL</title>
  5.     <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  6. <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css">
  7.     <script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
  8. <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
  9. </head>
  10. <body>
  11. <div class="container">
  12. <h1>Laravel 5 - Autocomplete Mutiple Fields Using jQuery, Ajax and MySQL</h1>
  13. {!! Form::open() !!}
  14.     
  15. <table class="table table-bordered">
  16. <tr>
  17. <th><input class='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><input type='checkbox' class='chkbox'/></td>
  24. <td><span id='sn'>1.</span></td>
  25. <td><input class="form-control autocomplete_txt" type='text' data-type="countryname" id='countryname_1' name='countryname[]'/></td>
  26. <td><input class="form-control autocomplete_txt" type='text' data-type="country_code" id='country_code_1' name='country_code[]'/> </td>
  27. </tr>
  28. </table>
  29. <button type="button" class='btn btn-danger delete'>- Delete</button>
  30. <button type="button" class='btn btn-success addbtn'>+ Add More</button>
  31. {!! Form::close() !!}
  32. </div>
  33. <script type="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><input type='checkbox' class='chkbox'/></td>";
  43. data+="<td><span id='sn"+i+"'>"+count+".</span></td>";
  44. data+="<td><input class='form-control autocomplete_txt' type='text' data-type='countryname' id='countryname_"+i+"' name='countryname[]'/></td>";
  45. data+="<td><input class='form-control autocomplete_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>

Manual Laravel Autocomplete search from Database

PHP Bootstrap - dynamic autocomplete tag input using jquery plugin

Phone: (+91) 8800417876
Noida, 201301