Welcome to our comprehensive guide on PHP AJAX Live Search! In this tutorial, we'll learn how to create a live search feature using PHP and AJAX. This tutorial is designed for beginners and intermediate learners, so don't worry if you're new to these concepts. Let's dive in!
AJAX (Asynchronous JavaScript and XML) is a technique used in web development to update parts of a web page without requiring a full page refresh. This makes for smoother, faster user experiences.
AJAX allows PHP to send and receive data asynchronously, which is particularly useful for live search functionality. We can send a search query to the server, receive the results, and update the web page without causing a full page reload.
search.php) and an HTML file (e.g., index.html).Let's create a simple HTML form for our search.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP AJAX Live Search</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>PHP AJAX Live Search</h1>
<form id="search-form">
<input type="text" id="search-input" placeholder="Search...">
</form>
<div id="search-results"></div>
<script src="script.js"></script>
</body>
</html>We'll create a PHP script to process the search query and return the results.
<?php
// This is a simple example. In a real-world project, you'd likely be querying a database.
$search_term = $_GET['term'];
$results = array();
// Push some search results into the $results array for demonstration purposes.
$results[] = "Result 1";
$results[] = "Result 2";
$results[] = "Result 3";
echo json_encode(array('results' => $results));
?>Now, let's write the JavaScript code to handle the AJAX request and update the search results.
$(document).ready(function() {
$('#search-form').on('submit', function(e) {
e.preventDefault();
var search_term = $('#search-input').val();
$.ajax({
url: 'search.php',
data: { term: search_term },
dataType: 'json',
success: function(data) {
var results_html = '';
data.results.forEach(function(result) {
results_html += `<li>${result}</li>`;
});
$('#search-results').html(results_html);
}
});
});
});Save your files, then open index.html in your browser. You should see a simple search form. Start typing, and you'll see the search results update dynamically thanks to AJAX and PHP!
What is AJAX?
What does AJAX stand for?