jQuery UI autocomplete with PHP and AJAX

The autocomplete functionality shows the suggestion list according to the entered value. The user can select a value from the list.

With jQuery UI you can easily add autocomplete widget to the input element. Navigate to the suggestion list either by mouse or keyboard arrow keys.

It has the various options that allow customizing the widget.

You can fix the suggestion source value while initializing in this case whenever the user typed any character then it searches the value within the given source value or you can make it dynamic with AJAX.

In this tutorial, I show how you can add jQuery UI autocomplete on the textbox and select single or multiple values from the suggestion list.

jQuery UI autocomplete with PHP and AJAX


Contents

  1. Table structure
  2. Configuration
  3. Download and Include
  4. HTML
  5. PHP
  6. jQuery
  7. Demo
  8. Conclusion

1. Table structure

I am using users table in the example.

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `username` varchar(100) NOT NULL,
  `name` varchar(100) NOT NULL,
  `email` varchar(100) 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. Download and Include

  • Download jQuery and jQuery UI libraries.
  • With jQuery and include jQuery UI library script and CSS files in the <head> section or end of </body>.
<!-- Script -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- jQuery UI -->
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

4. HTML

Created 4 input boxes –

  • The first textbox to add autocomplete widget.
  • The second is used to show selected user id from the suggestions list.
  • The third textbox to add multiple autocomplete.
  • The forth textbox to show selected multiple user ids.

Completed Code

<table>
  <tr>
    <td>Single selection</td>
    <td><input type='text' id='autocomplete' ></td>
  </tr>

  <tr>
    <td>Selected User id</td>
    <td><input type='text' id='selectuser_id' /></td>
  </tr>

  <tr>
    <td>Multiple Selection</td>
    <td><input type='text' id='multi_autocomplete' ></td>
  </tr>

  <tr>
    <td>Selected User ids</td>
    <td><input type='text' id='selectuser_ids' /></td>
  </tr>

</table>

5. PHP

Create a new fetchData.php file.

On the basis of POST search value fetch records from the users Table. Declare an Array variable $response and initialize it with an associative array where pass the  $row['id'] in value key and  $row['name'] in label key.

Completed Code

<?php

include "config.php";

if(isset($_POST['search'])){
 $search = $_POST['search'];

 $query = "SELECT * FROM users WHERE name like'%".$search."%'";
 $result = mysqli_query($con,$query);

 $response = array();
 while($row = mysqli_fetch_array($result) ){
   $response[] = array("value"=>$row['id'],"label"=>$row['name']);
 }

 echo json_encode($response);
}

exit;

NOTE – Remove value key from the array if you only want to work it name e.g. $response[] = array("label"=>$row['name']);


6. jQuery

Initialize

Initialize jQuery UI autocomplete on the <input id='autocomplete'> and <input id='multi_autocomplete'> by calling autocomplete() method.

Create 2 functions

  • split() – Return an array by splitting the value.
  • extractLast() – Select the last value from array.

Fetch source

Single Selection

Use source option to fetch users name when the key is got pressed. Get the typed value with request.term and pass it in AJAX.

Pass the AJAX response in response() method.

Multiple Selection

Get the last input value from the input box using extractLast() function and send AJAX request to fetch records.

Item Selection

Single Selection

Need to disable the default select functionality because when an option is been selected then the value is been shown on the screen instead of the label if the value is been defined.

Define select option and store the selected item value to <input type='text' id='seluserid' > and set label to autocomplete element.

Multiple Selection

Split the input box values and remove last value. Push ui.item.label and assign in the $('#multi_autocomplete').

Similarly, add ui.item.value in $('#selectuser_ids').

Completed Code

$( function() {

 // Single Select
 $( "#autocomplete" ).autocomplete({
  source: function( request, response ) {
   // Fetch data
   $.ajax({
    url: "fetchData.php",
    type: 'post',
    dataType: "json",
    data: {
     search: request.term
    },
    success: function( data ) {
     response( data );
    }
   });
  },
  select: function (event, ui) {
   // Set selection
   $('#autocomplete').val(ui.item.label); // display the selected text
   $('#selectuser_id').val(ui.item.value); // save selected id to input
   return false;
  }
 });

 // Multiple select
 $( "#multi_autocomplete" ).autocomplete({
    source: function( request, response ) {
                
      var searchText = extractLast(request.term);
      $.ajax({
         url: "fetchData.php",
         type: 'post',
         dataType: "json",
         data: {
           search: searchText
         },
         success: function( data ) {
           response( data );
         }
       });
    },
    select: function( event, ui ) {
        var terms = split( $('#multi_autocomplete').val() );
                
        terms.pop();
                
        terms.push( ui.item.label );
                
        terms.push( "" );
        $('#multi_autocomplete').val(terms.join( ", " ));

        // Id
        terms = split( $('#selectuser_ids').val() );
                
        terms.pop();
                
        terms.push( ui.item.value );
                
        terms.push( "" );
        $('#selectuser_ids').val(terms.join( ", " ));

        return false;
     }
           
 });

});
function split( val ) {
   return val.split( /,\s*/ );
}
function extractLast( term ) {
   return split( term ).pop();
}

NOTE – Remove select option if you have not return value key from the AJAX file.


7. Demo

Enter the value in the first and third input box and select value from the suggestion list.


8. Conclusion

The autocomplete widget gives suggestions to the user while searching value in the input element.

In the example, I customize the widget selection and store the selection value in the element for further processing.

You can learn more about this plugin from here.

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

Related Post

Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  

18 Comments

  1. Stefano said:

    Good morning mr Yogesh,
    i’ve read your tutorial about the autocomplete form with jquery, php and my_sqli,
    but I’m sure that I have not used properly, because the input text when I write something inside don’t append nothing on the bottom of the input text.
    The console say that I have not errors in the code, but in the js consoles appears a notice that says:

    ‘XHR finished loading: POST ‘in my_file’ at jquery.min.js:4

    More I write in the input text more of this notices I have.

    May I have your help please for getting no more trouble in this issue?
    I hope that you find the time to write me back,

    Best regards,

    Stefano Pirastru

    January 20, 2018
    Reply
  2. Manolo said:

    Hello
    I congratulate you for the work, I have detected an error when downloading the example, in the fetchdata.php page, the database you are calling is another ..

    $query = “SELECT * FROM user_depart WHERE name like’%”.$search.”%'”;

    es users

    January 26, 2018
    Reply
    • Yogesh Singh said:

      Hi Manolo,
      Thanks for mentioning the issue in the file.
      I have updated the download files.

      January 26, 2018
      Reply
  3. Ravindra said:

    Can you please give an example for multiple values selection. It would be great help.

    February 28, 2018
    Reply
    • Yogesh Singh said:

      Hi Ravindra,
      I will try to publish a tutorial on this in next few days. Subscribe to the blog to get notified.

      February 28, 2018
      Reply
      • Yogesh Singh said:

        I have updated the tutorial and cover multiple values selection from jQuery UI autocomplete.

        March 2, 2018
        Reply
  4. Nicolas said:

    Show, muito show!!!!
    Parabéns

    October 22, 2018
    Reply
  5. linh said:

    this work very very well for me.
    Is this example have any thing to adjust the time suggesstion display?

    February 3, 2019
    Reply
  6. cetipabo said:

    Is this working with bootstrap 3 ??
    it doesn’t seem to…looks like i have a css issue because i see the dropdown menu but there is no value in it

    February 14, 2019
    Reply
      • kiki koko said:

        forget what i said, i made a mistake in the javascript side. i can now confirm that it works 100%.

        Sorry again !

        February 16, 2019
        Reply
        • Yogesh Singh said:

          Good to hear that your problem is now solved.

          February 16, 2019
          Reply
  7. Tumelo said:

    Hi, I have question. How can I limit the number of select items to 4 before saving them to the DB.

    March 14, 2019
    Reply
    • Yogesh Singh said:

      You can handle it from ‘source’ option before sending AJAX request.

      March 15, 2019
      Reply

Leave a Reply

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