Create autocomplete search with AngularJS and PHP

The autocomplete search box suggests data options to the user based on its input.

From there, it can select the option.

In the demonstration, I am creating a search box and display a suggestion list whenever the user input value in the search box. If a user clicks outside the suggestion list then hide it.

Set a selected value to the search box when an option gets selected.

I am using PHP with AngularJS to fetch records.

Create autocomplete search with AngularJS and PHP


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

1. Table structure

I am using users table and added some records.

CREATE TABLE `users` (
  `username` varchar(80) NOT NULL,
  `name` varchar(80) NOT NULL,
  `email` varchar(80) NOT NULL

2. Configuration

Create a new config.php file for database configuration.

Completed Code


$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());


Add ng-click='containerClicked()' on <div class='container'> to detect outside click of a search box and suggestion list <ul><li>.

Create a textbox element and for display, suggestion created the <ul> <li>.

  • On textbox defined ng-keyup='fetchUsers()‘ and ng-model directive. Also, add ng-click='searchboxClicked($event)'.
  • Show list of suggestion result on <li> using ng-repeat directive. Define ng-click directive which calls setValue($index,$event).

Completed Code

<body ng-app='myapp'>

  <div class='container' ng-controller="fetchCtrl" ng-click='containerClicked();' >
    <input type='text' 
          placeholder='Enter text'><br>
    <ul id='searchResult' >
      <li ng-click='setValue($index,$event)' 
          ng-repeat="result in searchResult" >
          {{ }}

4. CSS

  width: 100%; 
  height: 300px;

  list-style: none;
  padding: 0px;
  width: 250px;
  position: absolute;
  margin: 0;

#searchResult li{
  background: lavender;
  padding: 4px;
  margin-bottom: 1px;

#searchResult li:nth-child(even){
  background: cadetblue;
  color: white;

#searchResult li:hover{
  cursor: pointer;

  padding: 5px;
  width: 250px;
  letter-spacing: 1px;

5. PHP

Create a new getData.php file.

Search value on users table according to POST value and limit query result to 5. Initialize the array with the users name and return a JSON value.

Completed Code


include 'config.php';

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

$search = mysqli_real_escape_string($con,$data->searchText);

// Fetch 5 records
$sel = mysqli_query($con,"select * from users where name like '%".$search."%' limit 5");
$data = array();

while ($row = mysqli_fetch_array($sel)) {
  $data[] = array("name"=>$row['name']);

echo json_encode($data);

6. Script

Defined 4 methods in the controller –

  • fetchUsers() – This function is been called when keydown event trigger on the input box.

From here, check the input search text length if it is 0 then empty the $scope.searchResult otherwise send $http request where pass input value $scope.searchText as data. Initialize $scope.searchResult with on successfully callback.

  • setValue() – This function is called when an option gets selected from suggestion list. Initialize $scope.searchText with $scope.searchResult[index].name (selected value) and empty $scope.searchResult. Execute $event.stopPropagation() to stop parent click from trigger.
  • searchboxClicked() – Call on search box click. From here, execute $event.stopPropagation() to stop parent click from trigger.
  • containerClicked() – Call on <div class='container'> click. Empty the $scope.searchResult.

Completed Code

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

fetch.controller('fetchCtrl', ['$scope', '$http', function ($scope, $http) {
   // Fetch data
   $scope.fetchUsers = function(){
      var searchText_len = $scope.searchText.trim().length;

      // Check search text length
      if(searchText_len > 0){
           method: 'post',
           url: 'getData.php',
           data: {searchText:$scope.searchText}
         }).then(function successCallback(response) {
           $scope.searchResult =;
         $scope.searchResult = {};

   // Set value to search box
   $scope.setValue = function(index,$event){
      $scope.searchText = $scope.searchResult[index].name;
      $scope.searchResult = {};

   $scope.searchboxClicked = function($event){

   $scope.containerClicked = function(){
      $scope.searchResult = {};

7. Demo

View Demo

8. Conclusion

The autocomplete search allows the user to search on the list and select a value from the suggestions.

Define ng-click on the parent to detect outside of the suggestion list and search box. Stop the parent click from trigger using .stopPropagation() when clicked on the suggestion list or search box.

You can check my earlier tutorial to learn the implementation of this functionality with jQuery.

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