Create autocomplete search with AngularJS and PHP

The autocomplete functionality gives the user suggestions based on its input. From there, it can select an option.

In the demonstration, I am creating a search box and display suggestion list whenever the user input value in the search box.

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

For implementing this functionality I am using AngularJS and PHP.

Create autocomplete search with AngularJS and PHP


Contents

  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 in the tutorial 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
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

 

2. Configuration

Create a new config.php file.

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 a textbox element and for display, suggestion created the <ul> <li>.

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

Completed Code

<body ng-app='myapp'>

 <div ng-controller="fetchCtrl">
 
  <input type='text' ng-keyup='fetchUsers()' ng-model='searchText'><br>
  <ul id='searchResult' >
   <li ng-click='setValue($index)' ng-repeat="result in searchResult" >{{ result.name }}</li>
  </ul>
 
 </div>
 
</body>

 

4. CSS

#searchResult{
 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;
}

input[type=text]{
 padding: 5px;
 width: 250px;
 letter-spacing: 1px;
}

 

5. PHP

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

<?php

include 'config.php';

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

$search = $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 two methods in the controller –

  • fetchUsers() – This function is been called when keydown event trigger on the input box. From here send $http request where pass input value $scope.searchText as data. Initialize $scope.searchResult with response.data 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.

Completed Code

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

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

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

 

7. Demo

Enter text in the textbox.


 

8. Conclusion

The autocomplete feature allows the user to search and select an option from the suggestion list whether it know the exact value or not.

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

Related Post

Spread the love

Be First to Comment

Leave a Reply

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