How To Use jQuery Autocomplete With Ajax

Are you looking to integrate jQuery Autocomplete on your website? jQuery Autocomplete is like Google Search where a user enters some letters and result set matching with typed letters are pre-populated.

jQuery UI provides Autocomplete feature. To use this feature you need to use JS and CSS files provided by them.

In this short tutorial, we will take a small example and show you how to use jQuery Autocomplete with Ajax.

As an example, let’s take one text field. When a user starts entering a letter in this field, pre-populated data should appear from which the user can select a specific one.

How to Use jQuery Autocomplete with Ajax

Let’s say our text field is for a user’s first name. You have to search for the first name and records of names are stored in the database.

Create a index.html file and add the code below in it.

    <title>jQuery Autocomplete</title>
    <link rel="stylesheet" href="" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="//">
    <div class="container">
        <div class="row">
            <div class="col-md-2"></div>
            <div class="col-md-8">
                <div class="form-group">
                    <label for="exampleInputFname">First Name</label>
                    <input type="text" class="form-control" id="fnames" placeholder="First Name" name="fname">
            <div class="col-md-2"></div>
    <script type="text/javascript" src=""></script>
    <script type="text/javascript" src=""></script>
    <script src="" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

In the above HTML, I have given id “fnames” to the search box. On this id I would call the autocomplete method.

Next, let’s write JavaScript code which uses the autocomplete method, give a call to ajax file, grab the response from ajax file and append to search box.

<script type="text/javascript">
    $(function() {
            source: function(term, response){
                $.getJSON('search.php', { q: term }, function(data){ response(data); });

In the search.php file, we need to fetch records from the database, build the output in array format and finally use json_encode to encode the array. Don’t forget to use json_encode or else you will not get the expected output.

$q = $_REQUEST['q']['term'];

//search in the database and get the result.
//for e.x. your database result is ['sam', 'sandy']
//json_encode the final output
echo json_encode(['sam', 'sandy']);

I hope you understand how to use jQuery Autocomplete with Ajax in PHP. We would like to hear your thoughts in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

Leave a Reply

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