PHP - AJAX Auto Complete Search

Introduction

Hello there! Welcome to our journey into the world of programming with PHP and AJAX. Today, we're going to dive deep into creating an auto-complete search feature using PHP and AJAX. This tutorial is designed for beginners who have no prior experience in programming. So, let's get started!

PHP - AJAX Auto Complete Search

The XML Document

Before we can create our auto-complete search feature, we need to set up an XML document that will serve as our data source. An XML document is a collection of data stored in a structured format that can be easily read by both humans and machines. In this case, our XML document will contain a list of cities around the world.

<?xml version="1.0" encoding="UTF-8"?>
<cities>
    <city>New York</city>
    <city>Los Angeles</city>
    <city>Chicago</city>
    <city>Houston</city>
    <city>Phoenix</city>
    <city>Philadelphia</city>
    <city>San Antonio</city>
    <city>San Diego</city>
    <city>Dallas</city>
    <city>San Jose</city>
</cities>

Save this XML document as cities.xml in the same directory as your PHP file.

JavaScript Code

Now that we have our XML document ready, it's time to write some JavaScript code to fetch the data from the XML document and display it in a dropdown list when the user starts typing in the search box. We'll use AJAX to achieve this without refreshing the page.

First, let's create an HTML form with a search box and a dropdown list:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Auto Complete Search</title>
</head>
<body>
    <form id="searchForm">
        <input type="text" id="searchBox" onkeyup="showSuggestions(this.value)">
        <select id="suggestionList"></select>
    </form>
    <script src="autocomplete.js"></script>
</body>
</html>

Next, let's write the JavaScript code in a separate file called autocomplete.js:

function showSuggestions(str) {
    if (str.length == 0) {
        document.getElementById("suggestionList").innerHTML = "";
        return;
    } else {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("suggestionList").innerHTML = this.responseText;
            }
        };
        xmlhttp.open("GET", "get_suggestions.php?q=" + str, true);
        xmlhttp.send();
    }
}

In this code, we define a function called showSuggestions that takes a string as input. When the user types something in the search box, this function is called with the input value. If the input length is zero, we clear the suggestion list. Otherwise, we create an XMLHttpRequest object to send an AJAX request to a PHP file called get_suggestions.php with the query parameter q set to the input value.

PHP Code

Now, let's move on to the PHP side of things. We'll create a file called get_suggestions.php that will handle the AJAX request and return the matching city names as an HTML list:

<?php
$query = $_GET['q'];
$xml = simplexml_load_file('cities.xml');
$matchingCities = array();

foreach ($xml->city as $city) {
    if (strpos(strtolower($city), strtolower($query)) !== false) {
        $matchingCities[] = $city;
    }
}

echo '<ul>';
foreach ($matchingCities as $city) {
    echo '<li>' . $city . '</li>';
}
echo '</ul>';
?>

In this PHP code, we first load the XML document using the simplexml_load_file function. Then, we loop through each city in the XML document and check if the query string is found within the city name (ignoring case sensitivity). If a match is found, we add the city to the $matchingCities array. Finally, we output an unordered list (<ul>) containing the matching city names as list items (<li>).

That's it! You now have a basic auto-complete search feature using PHP and AJAX. Remember to place all three files (index.html, autocomplete.js, and get_suggestions.php) in the same directory and open index.html in a web browser to see the search box in action.

As you continue your journey in programming, you'll find that there are many ways to implement auto-complete features, such as using frameworks like React or Angular, or even using modern frontend libraries like Vue.js or Svelte. But for now, this simple example should give you a solid foundation to build upon.

Happy coding!

Credits: Image by storyset