How to Auto-populate Dropdown with AngularJS and PHP

By creating dynamic dependent dropdown the user is restricted to select an item to view data on another dropdown element.

Based on each selection data is changed in the dropdown.

The common example of this – country and state element in the form. According to the selected country state is been auto-populated.

I am using the $http service in AngularJS to send a request to fetch records from MySQL database with PHP.

In the demonstration, I am creating two dropdowns – state and users. According to the state selected from the first dropdown auto-populate users list in the second dropdown.

How to Auto-populate Dropdown with AngularJS and PHP


Contents

  1. Table structure
  2. Configuration
  3. HTML
  4. PHP
  5. Script
  6. Demo
  7. Conclusion

1. Table structure

I am using users table in the example.

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

2. Configuration

Create a config.php to define database connection.

Completed Code

<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
 die("Connection failed: " . mysqli_connect_error());
}

3. HTML

Create two dropdowns –

In the first dropdown added state name in options. To auto-populate data on the second dropdown on option selection added ng-change='fetchUsers()' and ng-model='state'.

In the second dropdown use ng-repeat to read values from usersList and create options.

Completed Code

<div ng-controller="fetchCtrl">
 
 <table>
   <tr>
     <td>State :</td>
     <td>
       <select ng-model='state' ng-change='fetchUsers()'>
         <option value='0'>-- Select State --</option>
         <option value='1'>Gujarat</option>
         <option value='2'>Madhya Pradesh</option>
         <option value='3'>Maharashtra</option>
         <option value='4'>Chhattisgarh</option>
         <option value='5'>Haryana</option>
       </select>
     </td>
   </tr>

   <tr>
     <td>User :</td>
     <td>
       <select >
         <option value='0'>-- Select User --</option>
         <option ng-repeat="user in usersList" value='{{ user.id }}' >{{ user.name }}</option>
       </select>
     </td>
   </tr>
 </table>
 
</div>

4. PHP

Create a getData.php file.

Fetch records from users table according to the state id. Initialize the Array with id and name of the user.

Return the JSON response.

Completed Code

<?php

include 'config.php';

$data = json_decode(file_get_contents("php://input"));

$state = mysqli_real_escape_string($con,$data->state);

$result = mysqli_query($con,"SELECT id,name FROM users WHERE state=".$state);
$data = array();

while ($row = mysqli_fetch_assoc($result)) {
  $data[] = array("id"=>$row['id'], "name"=>$row['name']);
}

echo json_encode($data);

5. Script

Create a fetchUsers method which calls when state selected from the dropdown.

Send $http request and where pass the $scope.state. On successfully callback assign response.data in $scope.usersList.

Completed Code

var fetch = angular.module('myapp', []);

fetch.controller('fetchCtrl', ['$scope', '$http', function ($scope, $http) {
  
  $scope.state = '0';
  
  // Fetch data
  $scope.fetchUsers = function(){
 
    $http({
      method: 'post',
      url: 'getData.php',
      data: {state:$scope.state}
    }).then(function successCallback(response) {
      $scope.usersList = response.data;
    });

  }
 
}]);

6. Demo

Select a state.


7. Conclusion

In this tutorial, I auto-populated data on the dropdown element but you can use any other HTML element e.g. textbox, textarea.

If you like to auto-populate data on more than one HTML element then attach the event to the element and send $http request to fetch records.

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