Skip to main content

Laravel 5 - Autocomplete Mutiple Fields Using jQuery, Ajax and 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>

Comments

Popular posts from this blog

Async Queues In Laravel

Push a function/closure to the background. For Laravel 5.4, check the 0.6 branch For Laravel 5.3, check the 0.5 branch Just like the 'sync' driver, this is not a real queue driver. It is always fired immediatly. The only difference is that the closure is sent to the background without waiting for the response. This package is more usable as an alternative for running incidental tasks in the background, without setting up a 'real' queue driver. Note: This is using the DatabaseQueue, so make sure you set that up first, including migrations. Install Require the latest version of this package with Composer composer require barryvdh/laravel-async-queue Add the Service Provider to the providers array in config/app.php Barryvdh\Queue\AsyncServiceProvider::class, You need to create the migration table for queues and run it. $ php artisan queue:table $ php artisan migrate You should now be able to use the async driver in config/queue.php. Use the same config a...

Laravel working with Queues

What are queues in web development? Queues allow you to defer/postpone the processing of a time consuming task, such as sending an e-mail, until a later time, thus drastically speeding up the web requests to your application, which returns a response and serves the client significantly faster than it would be if the task ran synchronously. The Laravel Queue component provides a unified API across a variety of different queue services. There are different queue services. Some of them are hosted elsewhere, but some of them can be self-hosted, such as Beanstalkd, which I'll cover here. How do they work behind the scenes? Once you push a job onto the queue (from somewhere within your code, e.g. send an email after user has registered), all that the client has to wait for is for job to be pushed onto the queue service that is listening for jobs, and doesn't have to wait for the queue service to finish the job itself. The most trivial example would be a McDonalds employee ...

The Coolest New Tech In 2018

The world of tech is always evolving, and each new year comes with all sorts of innovations and breakthroughs from some of the coolest and most prestigious companies in the world. This year is no different, and more information is starting to come out about some of the coolest gadgets releasing in 2018. All of this cool new technology is set to be released to consumers sometime this year, and the general excitement is already making waves online. Out of all of these cool new gadgets, which of these releases is building the most hype? The biggest names in tech are looking to dazzle consumers with the latest revolutionary technologies, but there are also some lesser known companies who are showcasing their newest products in order to make a name for themselves. It's up to the people to decide what new technologies are going to take 2018 by storm and which ones will ultimately be forgotten. This Reverse Microwave Can Quick-Freeze Food And Drinks ...