How can PHP be used to handle form submissions and database searches on the same page without reloading?

To handle form submissions and database searches on the same page without reloading, you can use AJAX to send the form data to a PHP script that processes the data and performs the database search. The PHP script can then return the search results back to the page without reloading.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Process form data
    $searchTerm = $_POST["search_term"];
    
    // Perform database search
    // Connect to database, run query, fetch results
    
    // Return search results
    echo json_encode($searchResults);
    exit;
}
?>

<!-- HTML form -->
<form id="searchForm">
    <input type="text" name="search_term">
    <button type="submit">Search</button>
</form>

<div id="searchResults"></div>

<script>
document.getElementById("searchForm").addEventListener("submit", function(event) {
    event.preventDefault();
    
    var formData = new FormData(this);
    
    fetch("search.php", {
        method: "POST",
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        document.getElementById("searchResults").innerHTML = data;
    });
});
</script>