Auto populate Dropdown with jQuery AJAX in Laravel

Autopopulating values require when need to load records on child element based on parent element value.

Element values replace with new items whenever parent element value changes.

In this tutorial, I show how you can auto-populate dropdown with jQuery AJAX in Laravel.

Auto populate dropdown with jQuery AJAX in Laravel


Contents

  1. Table structure
  2. Database Configuration
  3. Model
  4. Controller
  5. Route
  6. View
  7. Output
  8. Conclusion

 


1. Table structure

I am using two tables in the examples –

department table – Store department names.

CREATE TABLE `department` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `depart_name` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

employees table – Store employees details and their department.

CREATE TABLE `employees` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(80) NOT NULL,
  `name` varchar(80) NOT NULL,
  `email` varchar(80) NOT NULL,
  `department` int(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Database Configuration

Open .env file.

Specify the host, database name, username, and password.

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

3. Model

Create a Page Model.

php artisan make:model Page

To access MySQL database added use Illuminate\Support\Facades\DB;.

Here, create two methods –

  • getDepartment – Select all records from department table and return it.
  • getdepartmentEmployee – Select all records from employees table according to department id and return it.

Completed Code

<?php

namespace App;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;

class Page extends Model {

   // Fetch departments
   public static function getDepartment(){

     $value=DB::table('department')->orderBy('id', 'asc')->get(); 

     return $value;
   }

   // Fetch employee by department id
   public static function getdepartmentEmployee($departmentid=0){

     $value=DB::table('employees')->where('department', $departmentid)->get();

     return $value;
   }

}

4. Controller

Create a PagesController controller.

php artisan make:controller PagesController

Added use App\Page; to access Page Model.

Here, create two methods –

  • index – Call Page Model getDepartment() method to get all departments.

Load index view and pass $departmentData.

  • getEmployees – This method used to handle AJAX request. Pass $departmentid in getdepartmentEmployee() method to get the employees list.

Return JSON response.

Completed Code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Page;

class PagesController extends Controller {

   public function index(){

     // Fetch departments
     $departmentData['data'] = Page::getDepartment();

     // Load index view
     return view('index')->with("departmentData",$departmentData);
   }

   // Fetch records
   public function getEmployees($departmentid=0){

     // Fetch Employees by Departmentid
     $userData['data'] = Page::getdepartmentEmployee($departmentid);

     echo json_encode($userData);
     exit;
   }
}

5. Route

Open routes/web.php file.

Here, define two routes –

  • /
  • /getEmployees/{id} – This route use in jQuery AJAX request to get employees list.
<?php

Route::get('/', 'PagesController@index'); // localhost:8000/
Route::get('/getEmployees/{id}', 'PagesController@getEmployees');

6. View

Create a new index.blade.php file in resources/views/ directory.

HTML –

Create two <select > elements –

  • In the first <select > display departments name by looping on $departmentData['data'].
  • The second <select > is used to display employee names according to the selected department using jQuery.

jQuery –

Define change event on the first dropdown (<select id='sel_depart'>).

Read selected value and empty the second <select id='sel_emp'> element all options except first.

Send AJAX GET request to 'getEmployees/' and also pass id value.

On successful callback check response length if it is greater than 0 then loop on response. Create options and append in #sel_emp selector.

Completed Code

<!DOCTYPE html>
<html>
   <head>
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
   </head>
   <body>

     <!-- Department Dropdown -->
     Department : <select id='sel_depart' name='sel_depart'>
       <option value='0'>-- Select department --</option>
 
       <!-- Read Departments -->
       @foreach($departmentData['data'] as $department)
         <option value='{{ $department->id }}'>{{ $department->depart_name }}</option>
       @endforeach

    </select>

    <br><br>
    <!-- Department Employees Dropdown -->
    Employee : <select id='sel_emp' name='sel_emp'>
       <option value='0'>-- Select Employee --</option>
    </select>

    <!-- Script -->
    <script type='text/javascript'>

    $(document).ready(function(){

      // Department Change
      $('#sel_depart').change(function(){

         // Department id
         var id = $(this).val();

         // Empty the dropdown
         $('#sel_emp').find('option').not(':first').remove();

         // AJAX request 
         $.ajax({
           url: 'getEmployees/'+id,
           type: 'get',
           dataType: 'json',
           success: function(response){

             var len = 0;
             if(response['data'] != null){
               len = response['data'].length;
             }

             if(len > 0){
               // Read data and create <option >
               for(var i=0; i<len; i++){

                 var id = response['data'][i].id;
                 var name = response['data'][i].name;

                 var option = "<option value='"+id+"'>"+name+"</option>"; 

                 $("#sel_emp").append(option); 
               }
             }

           }
        });
      });

    });

    </script>
  </body>
</html>

7. Output


8. Conclusion

Define change event on the parent element and according to the selected value fetch records for child element with jQuery AJAX.

You can modify the code if you want to do this with more than two dropdowns. For this, you need to define change event accordingly and fetch records with jQuery AJAX.

If you found this tutorial helpful then don't forget to share.

Related Post

Spread the love
  • 2
  •  
  •  
  •  
  • 1
  •  

Be First to Comment

Leave a Reply

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