PHP Ajax Auto Complete Search

please click here for more wordpress cource

Sure, I can help you with that.

Auto-complete search using PHP and Ajax can be achieved using the following steps:

  1. Create a database table to store the search keywords and their corresponding results.
  2. Create a PHP script that fetches the search results from the database based on the user’s input.
  3. Use Ajax to call the PHP script and display the search results on the web page.

Here is an example code that demonstrates how to create an auto-complete search using PHP and Ajax:

index.php

<!DOCTYPE html>
<html>
<head>
	<title>Auto Complete Search</title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
	<script>
		$(document).ready(function(){
			$("#search").keyup(function(){
				var keyword = $(this).val();
				$.ajax({
					url: "search.php",
					method: "POST",
					data: {keyword:keyword},
					success:function(data){
						$("#result").html(data);
					}
				});
			});
		});
	</script>
</head>
<body>
	<h1>Auto Complete Search</h1>
	<input type="text" id="search" placeholder="Search...">
	<div id="result"></div>
</body>
</html>

search.php

<?php
// Connect to the database
$conn = mysqli_connect("localhost", "username", "password", "database");

// Fetch the search results
if(isset($_POST['keyword'])){
	$keyword = $_POST['keyword'];
	$query = "SELECT * FROM search WHERE keyword LIKE '%$keyword%' LIMIT 5";
	$result = mysqli_query($conn, $query);
	while($row = mysqli_fetch_array($result)){
		echo '<a href="'.$row['url'].'">'.$row['title'].'</a><br>';
	}
}
?>

In the above code, we have a simple HTML file that contains an input field and a div where we will display the search results. When the user types something in the input field, we use jQuery to send an Ajax request to the PHP script “search.php” along with the keyword entered by the user. The PHP script then fetches the search results from the database and returns them to the Ajax call in the form of HTML links, which are then displayed in the div element on the web page.

Please note that this is just a basic example, and you may need to modify it according to your specific requirements. Also, make sure to sanitize and validate user input to prevent SQL injection and other security vulnerabilities.

You may also like...

Popular Posts

Leave a Reply

Your email address will not be published. Required fields are marked *