Auto populate Dropdown with jQuery AJAX in Laravel Example

48

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.

Contents

  1. Table structure
  2. Database Configuration
  3. Model
  4. Controller
  5. Route
  6. View

1. Table structure

I am using two tables in the examples –

department table – Store department names.

employees table – Store employees details and their department.


2. Database Configuration

Open .env file.

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


3. Model

Create a Page Model.

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


4. Controller

Create a PagesController controller.

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


5. Route

Open routes/web.php file.

Here, define two routes –

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


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

Leave A Reply

Your email address will not be published.