Autocomplete using PHP and Ajax

autocomplete using php and ajax

In the previous tutorials, we learned about uploading an image using AJAX and Javascript. So in this tutorial, we’ll see autocomplete using PHP and Ajax.

Autocomplete plays an important role in web development and with the help of ajax we can let users get an excellent experience. So let’s first understand what autocomplete is?

When a user types a particular character(s) to search in the text field and the system gives a list of matching contents without refreshing the page then that process is called autocomplete.

So, in this tutorial, we are going use mainly PHP, AJAX (using JQuery), HTML & CSS (optional in this demo)

Steps to be followed (in this tutorial) for autocomplete using PHP and Ajax-

  1. Create HTML form
  2. Use JQuery for Ajax to get a list of matching names
  3. Get the list of matching names using cURL and return to the user in the form of a list.

Creating HTML Form

<!DOCTYPE html>
<html>

<body>
    <h2>Demo Example</h2>
    <form action="" method="POST">
        <label for="name">Astronauts:</label><br>
        <input type="text" id="astronauts" name="astronauts">
        <div id="astronauts-list"></div>
        <input type="submit" value="Submit">
    </form>
</body>

</html>

We’ve used only one form field for the demo. In practical examples, there might be many more fields. Here, we have defined one text field for astronauts and this will suggest their names once we start tying.

Use JQuery for Ajax to get a list of matching names

There are different ways of fetching data using JQuery-

  1. Using regular way
  2. Using JQuery autocomplete() function
Using regular way
<script type="text/javascript">
    $(document).ready(function() {

        $("#astronauts").keyup(delay(function(e) {
            $.ajax({
                method: "POST",
                url: "response.php",
                dataType: "json",
                data: {
                    astronaut_name: $(this).val()
                }
            }).done(function(response) {
                $("#astronauts-list").show();
                var lists = '';
                $.each(response, function(key, val) {
                    lists += "<li onclick='highlightSelectedAstronauts(\"" + val + "\")'>" + val + "</li>";
                });
                $("#astronauts-list").html(lists);
            });
        }, 700));
    });

    function highlightSelectedAstronauts(val) {
        $("#astronauts").val(val);
        $("#astronauts-list").hide();
    }

    function delay(callback, ms) {
        var timer = 0;
        return function() {
            var context = this,
                args = arguments;
            clearTimeout(timer);
            timer = setTimeout(function() {
                callback.apply(context, args);
            }, ms || 0);
        };
    }
</script>

Here is the complete javascript code. Let’s understand it block by block.

So, when document loads, we initialize keyup event for our field “astronauts”. It means whenever user types then this keyup event gets triggered and it performs ajax operation.

In the ajax call, once we received response from PHP then we show all the matching astronauts in the form of list in “li” and on clicking any name that astronaut will be selected in the text field.

Here, we have also delayed the request (using delay function) to the server by few milliseconds because sometime user types the name very fast and ajax requests the server multiple time which takes time to fetch the actual result.

If the matching list is huge then it will eventually takes longer time than the short list. So, the solution is to delay the request to the server by few milliseconds which not only lowers the burden on the server but also respond very quickly..

Using JQuery autocomplete() function

To use jquery autocomplete we need to include jquery UI css and js files as well which can be downloaded at – https://jqueryui.com/download/

$(function() {
        $("#astronauts").autocomplete({
            delay: 700,
            source: function(request, response) {
                // Fetch data
                $.ajax({
                    url: "response.php",
                    type: 'post',
                    dataType: "json",
                    data: {
                        astronaut_name: request.term
                    },
                    success: function(data) {
                        response(data);
                    }
                });
            },
            select: function(event, ui) {
                // Set selection
                $('#astronauts').val(ui.item.value); // display the selected text
                return false;
            }
        });
    });

In this example, we have used jquery ui and autocomplete() function to fetch the list of astronauts.

So basically, we used same ajax call with few modifications like in the data parameter we used request.terms (only one object property available to request) to get the input value and then used response() callback to return the data received in the ajax call.

request object and response callback are two arguments supplied to source attribute using anonymous function in which request refers to the value currently in the text input and response is a callback with only a single argument: the data to suggest to the user.

Like in the first jQuery example we used delay function for ajax call to be executed for some time. Likewise, here in the autocomplete() as well we can pass delay parameter with value in milliseconds. This will prevent continuous call to server.

Once user get list of astronauts, user can click any name & that name will be updated in text box. This functionality is done via select: callback.

Get the list of matching names using cURL

<?php

$astronaut_name = strtolower($_POST['astronaut_name']);

$cURLConnection = curl_init('http://api.open-notify.org/astros.json');

curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);

$apiResponse = curl_exec($cURLConnection);
curl_close($cURLConnection);

$list = [];
$list_astros = json_decode($apiResponse, true);

if ($list_astros['message'] == 'success') {
    foreach ($list_astros['people'] as $key => $astronaut) {
        preg_match("/" . $astronaut_name . "/", strtolower($astronaut['name']), $output_array);

        if (!empty($output_array)) {
            array_push($list, $astronaut['name']);
        }
    }
}
echo json_encode($list);

In the above code we used cURL to get the list of astronauts. We can also fetch the list from database. But for the demo I think we can keep cURL for shorter code.

In the cURL request, we fetch the current astronauts which are currently present in the ISS (International Space Station). Once we get that list then we can start with collecting only that list which is currently matching with what user has requested.

In the next piece of code, we loop through each astronauts fetched using cURL and whatever the user has requested will be matched with each astronauts one by one and if it matches then that will be collected in the separate array and then using json_encode() function we’ll return json string to ajax call.

A caching system is suggested to store these astronauts because this cURL always fetches the same names.

Conclusion:

Giving user best experience when it comes to larger website is the good approach but that doesn’t mean the website should be fancy. User must not be irritated when he/she requires particular list and he/she has to keep waiting.

Autocomplete using PHP and ajax saves not only users time and but it also increases usability as well.