jQuery UI autocomplete with PHP and AJAX

The autocomplete functionality shows the suggestion list according to the entered value. You can choose a suggestion from the list. With jQuery UI you can easily add autocomplete widget to the input element. You can use your mouse or keyboard arrow keys to navigate the suggestion list. The widget has various options for customization.

You can set the suggestion source value while initializing the widget. This means it will search for values within the given source value whenever the user types any character. Alternatively, 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. Create a Table
  2. Create a file for Database connection
  3. Download and Include jQuery UI
  4. Create HTML elements for Autocomplete Initialization
  5. AJAX – Retrieving jQuery UI autocomplete Data
  6. jQuery – Implementing the jQuery UI Autocomplete
  7. Demo
  8. Conclusion

1. Create a Table

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

2. Create a file for Database connection

Create a config.php file for database connection.

<?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 jQuery UI

  • 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.6.0/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. Create HTML elements for Autocomplete Initialization

Created 4 input boxes –

  • The first textbox to add autocomplete widget.
  • The second textbox displays the user ID that was selected from the suggestions list.
  • The third textbox is to add multiple autocomplete.
  • The fourth textbox shows selected multiple user ids.
<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. AJAX – Retrieving jQuery UI autocomplete Data

To handle AJAX requests, create a fetchData.php file.

Retrieve records from the users table based on the “POST” search value. Declare an Array variable $response and initialize it with an associative array where pass the  $row['id'] to value key and  $row['name'] to label key.

<?php

include "config.php";

if(isset($_POST['search'])){
    $search = mysqli_real_escape_string($con,$_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 with name e.g. $response[] = array("label"=>$row['name']);


6. jQuery – Implementing the jQuery UI Autocomplete

Initialize jQuery UI autocomplete

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 autocomplete data

Single Selection

To fetch user names when a key is pressed, use the source option. Retrieve the typed value using request.term and pass it in the AJAX request. Then, pass the AJAX response in the 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').

$( 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;
         },
         focus: function(event, ui){
              $( "#autocomplete" ).val( ui.item.label );
              $( "#selectuser_id" ).val( ui.item.value );
              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

View Demo


8. Conclusion

The user experience on your website or application can be significantly enhanced by adding autocomplete functionality.
Using jQuery UI with PHP and AJAX makes it simple to implement this feature and customize it according to your requirements.

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

For more information about the jQuery UI autocomplete widget, you can visit the official website.

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

54 thoughts on “jQuery UI autocomplete with PHP and AJAX”

  1. 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

    Reply
  2. 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

    Reply
    • y si tienes mucha información en la bases de datos, lo que puedes hacer es la consulta poner un limit, ejemplo:

      $ query = “SELECT * FROM user_depart WHERE nombre como like’%”.$search.”%’ limit 8”;
      yo puse 8, por que quise que en el input en la lista solo mostrará 8 registro, pero puedes poner el número que desee.

      Reply
  3. 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

    Reply
  4. Hi Yogesh,
    Thank you for this script.
    The only thing is when you select a value from the suggestion list, it display an ID instead of a value. This means when your list is long (as in my case) and you select the wrong suggestion, you have to remove the ID and start over again.

    Is there a possibility that into this text field:
    stays the value when you go through the suggestion list?

    Thanks and regards
    DEM

    Reply
  5. Hi, first at all it is a good tool and here are my questions:
    1. How can I bold or color the matched part of the string in the label?
    2. How can I color every second label from the suggestions?
    Regards.

    Reply
  6. Can we have some test names to try in the demo? It looks nice, but I see no reference to them, so I can’t see if your code is producing the desired result.
    I’m sure it works, it’s just helpful to see it in action.

    Reply
  7. Hello greetings
    One question, how can I bring more than one piece of information?
    Search name and bring the uername and mail and id?

    regards

    Reply
  8. I downloaded your script but it is not working. When I do an inspection on the element, I see that autocomplete=”off”. Why is that? How to set this to “on”?

    Reply
  9. excelente, se deja modificar para los requerimientos que uno necesita, uno de los mejores aportes que he visto en mucho tiempo.

    gracias por ese excelente script

    Reply
  10. Thank you very much!
    When i use the keyboard arrow keys at the multiple selection, the previous selected names disappear. Do you have a solution for that? So it works the same as with the mouse use?

    Reply
  11. Thanks a lot for posting this tutorial. It works great from the start. It’s been a while since I’ve been heavily developing and it’s tutorials like this that are helping me get refreshed.

    Question: When names are added to the multi-selector the user ID’s aren’t updated if the user decides to delete a name from the selection…is there an easy way to handle this?

    Reply
  12. Bom dia, uma dúvida, se eu tenho 2 ou mais nomes iguais tipo tenho 2 Joao, só após digitar Joao B é que começa a aparecer a lista, agora se eu tiver 2 Joao Batista, só após digitar Joao Batista é que começa a aparecer a lista.

    Reply
  13. Hello, when you type the letter “e” a drop-down list appears, is it possible in this example to make appear next to the name also the id in parenthesis? Thank you

    Reply
  14. Hello, everything works fine, except the results box. It seems to be “stuck”.

    Let’s say I have “username” “John123” in my database. When I type “jo” in the field, I get the correct result. But when I continue and type “johx”, “John123” keeps showing as suggestion.

    I have tried different forms, databases, JQuery versions, but still the same issue.

    Can you please help with this ? Thank you

    Reply
  15. obrigado ao autor do post com pequenos ajustes conseguir usar esse codico obrigado amigo
    obs:estou usando MVC e uma querybuillder e ainda asim consegui implementar o codico
    bela ditatica parabens

    Reply
  16. Cool.. thank you very much.
    If you want to add scroll bars to the dropdown, use the following

    .ui-autocomplete {
    max-height: 150px;
    overflow-y: auto;
    /* prevent horizontal scrollbar */
    overflow-x: hidden;
    /* add padding to account for vertical scrollbar */
    padding-left: 5px;
    padding-right: 5px;
    }

    I saw that in stackoverflow

    Reply
  17. Man, your article is cool, but its not complete because of the problem when we navigate thru the list and the ID appears in the input.
    Its suppose to appear the label. Come on… its a bug!

    Reply
  18. If you want to set the Label instead of ID when navigating in the list, put that code before the select: “function (event, ui)”

    focus: function(event, ui){
    $( “#imput_name” ).val( ui.item.label );
    return false;
    },

    Reply

Leave a Comment