Creating a live data search feature on your website enhances user experience by providing real-time feedback as users type their queries. This tutorial will guide you through setting up a live search using PHP, and MySQL With Ajax. This feature is particularly useful for blogs or content-rich websites where users may need to find specific information quickly.
Step 1: Setting Up the Database
simple_search
and a table named countries for demonstration purposes. You can use phpMyAdmin or any MySQL client for this step.
CREATE TABLE countries
( id
int NOT NULL,
name
varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
-- Dumping data for table countries
--
INSERT INTO countries
(id
, name
) VALUES
(1, 'india'),
(2, 'indonesia'),
(3, 'ireland'),
(4, 'china'),
(5, 'chile'),
(6, 'iran');
Step 2: Setting Up the Database Connection
<?php
$server = "localhost";
$username = "root";
$password = "password";
$dbname = "simple-search";
#create connection
$con = mysqli_connect($server, $username, $password, $dbname);
Step 3: Setting Up the Frontend
<!DOCTYPE html>
<html>
<head>
<title>Simple search</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>
<div class="content-wrapper">
<div class="container-fluid">
<div class="row mt-5 justify-content-center">
<div class="col-sm-6 ">
<div class="card">
<div class="card-body">
<div class="form-row justify-content-center">
<div class="form-group col-lg-6 ">
<form>
<label for="name">Jorhat Engineering college search box</label>
<input class="form-control" id="search-country" list="countries" name="" placeholder="search country">
<datalist id="countries">
</datalist>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- bootstrap js -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="./main.js"></script>
</body>
</html>
Step 3: Setting Up the Backend
<?php
require_once "./dbconnect.php";
$input = $_POST['input'];
if (strlen($input) < 1) {
[
'countries' => ['id' => null, 'name' => 'No coutries found'],
];
return;
}
$sql = "SELECT id, name FROM countries WHERE name LIKE '%$input%'";
$res = $con->query($sql);
if ($res->num_rows < 1) {
echo json_encode([
'countries' => ['id' => null, 'name' => 'No country found'],
]);
return;
}
$countries = [];
while ($row = $res->fetch_object()) {
$countries[] = $row;
}
echo json_encode(['countries' => $countries]);
jQuery AJAX script to request live search
const searchCountry = document.querySelector('#search-country');
const dataList = document.querySelector('#countries');
searchCountry.addEventListener("keyup", function(event){
let value = event.target.value;
let input = new URLSearchParams();
input.append("input", value);
dataList.innerHTML = "";
axios.post('./get-countries.php', input)
.then((response) => {
let options = [];
for(let i=0; i < response.data.countries.length; i++) {
console.log(response.data.countries)
let option = `<option value=" ${ucFirst(response.data.countries[i].name)}">`;
options.push(option);
}
dataList.innerHTML = options.join(' ');
})
.catch((error) => {
console.log(error);
});
});
function ucFirst(str) {
console.log(str);
return str.split(' ').map(function(word){
return word[0].toUpperCase() + word.substr(1);
}).join(' ')
}