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>
Related Questions
- How can a PHP developer ensure that a user remains logged in even after leaving and returning to a website?
- How can FOR loops be utilized in PHP to achieve the desired result of displaying 3 results in each row of a table?
- What are some best practices for handling different file types, such as images, text, and PDF documents, in PHP download scripts?