DEV Community

Cover image for Autocomplete using PHP and Ajax
Programming Dive
Programming Dive

Posted on

Autocomplete using PHP and Ajax

Original & detailed post is written at 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.

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

  • Create HTML form
  • Use JQuery for Ajax to get a list of matching names
  • 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>
Enter fullscreen mode Exit fullscreen mode

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

<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>
Enter fullscreen mode Exit fullscreen mode

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

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);
Enter fullscreen mode Exit fullscreen mode

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.

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.

Top comments (0)