What are the best practices for integrating AJAX into a PHP-based search engine to enhance user experience?
Integrating AJAX into a PHP-based search engine can enhance user experience by allowing for real-time search results without refreshing the page. This can make the search process more efficient and user-friendly.
// HTML form for search input
<form id="searchForm">
<input type="text" name="searchQuery" id="searchQuery">
<button type="submit">Search</button>
</form>
// AJAX script to handle search request
<script>
$('#searchForm').submit(function(e) {
e.preventDefault();
var searchQuery = $('#searchQuery').val();
$.ajax({
url: 'search.php',
method: 'POST',
data: { searchQuery: searchQuery },
success: function(response) {
// Display search results on the page
$('#searchResults').html(response);
}
});
});
</script>
// PHP script (search.php) to process search query
<?php
if(isset($_POST['searchQuery'])) {
$searchQuery = $_POST['searchQuery'];
// Perform search query in the database
// Display search results
echo "<p>Search results for: $searchQuery</p>";
}
?>