How To Create Auto Completing Input In HTML With PHP AJAX And Javascript - letsbug
In this article we are making a auto completing input. We are going to use as usual HTML, CSS, Javascript but new thing is going to the PHP and AJAX.
We are using PHP on the server to get the data for our input. And with the help of AJAX we will make it look much better and the experience is going to be very smooth.
Before we start doing this project you should have a clear understanding of basics that is HTML, CSS, Javascript. And little bit of Ajax and PHP.
Prerequisite:
- Frontend
- HTML
- CSS
- JAVASCRIPT
- AJAX
- Backend
- PHP
Auto Completing Input
So without wasting our time let's just start. But before that let's see our project folder structure.
- autoCompleteInput
/server
- ajaxAutoComplete.php
- index.html
- main.js
- styles.css
In this project we have not focused on the styling but should always make some better looking UI even they are not important. Better UI will have a good impression of you.
let me give you a brief of the project. Here we have one text input. When there is any input in the text box it fires ajax call to the server gets the data related to the entered key or letter. In our case on entering any letter it suggest names of the cities from the server.
code: index.html
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>PHP | letsbug</title><link rel="stylesheet" href="./style.css"><script src="./main.js" defer></script></head><body><section><form autocomplete="false"><label for="city">Enter Your City</label><input type="text" id="city" name="city" list="cities" placeholder="eg. Pune" autocomplete="true"><datalist id="cities"></datalist></form></section></body></html>
code: styles.css
*,*::after,*::before {box-sizing: border-box;margin: 0;padding: 0;}body {font-family: 'Roboto', sans-serif;font-size: 16px;line-height: 1.5;color: #333;background-color: #eee;}section {width: 100%;margin: 0 auto;}section form {width: 20%;margin: 0 auto;padding: 2rem;background-color: #fff;border-radius: 5px;box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);}form label {display: block;margin-bottom: 10px;}form input[type="text"] {width: 100%;padding: 10px;border: 1px solid #ccc;border-radius: 4px;margin-bottom: 10px;}
code: main.js
const input = document.querySelector('#city');const suggestions = document.querySelector('#cities');input.addEventListener("keyup", () => {getSuggestions(input.value);})function getSuggestions(value) {if (value.length > 0) {const xhr = new XMLHttpRequest();xhr.open('GET',`http://localhost/college-practicals/slips/server/ajaxAutoComplete.php?city=${value}`);xhr.onload = () => {if (xhr.status === 200) {const cities = JSON.parse(xhr.responseText);showSuggestions(cities);}}xhr.send();}suggestions.innerHTML = '';}function showSuggestions(cities) {suggestions.innerHTML = '';cities.forEach(city => {suggestions.innerHTML += `<option>${city}</option>`;})}
code: ajaxAutoComplete.php
<?php$cities = array("Delhi","Mumbai","Bangalore","Chennai","Pune","Kolkata","Hyderabad","Ahmedabad","Chandigarh","Jaipur","Surat","Lucknow","Kanpur","Nagpur","Indore","Thane","Bhopal","Visakhapatnam","Vadodara","Ghaziabad","Ludhiana","Agra","Nashik","Faridabad","Meerut","Rajkot","Kalyan-Dombivali","Vasai-Virar","Varanasi","Srinagar","Aurangabad","Dhanbad","Amritsar","Raipur","Allahabad","Coimbatore","Jabalpur","Gwalior","Vijayawada","Madurai","Guwahati","Chandigarh","Hubli-Dharwad","Amroha","Moradabad","Gurgaon","Aligarh","Solapur","Ranchi","Jalandhar","Tiruchirappalli","Bhubaneswar","Salem","Warangal","Mira-Bhayandar","Thiruvananthapuram","Bhiwandi","Saharanpur","Guntur","Amravati","Bikaner","Noida","Jamshedpur","Bhilai Nagar","Cuttack","Kochi","Udaipur","Bhavnagar","Dehradun","Asansol","Nanded-Waghala","Ajmer","Jamnagar","Ujjain","Sangli","Loni","Jhansi","Pondicherry","Nellore","Jammu","Belagavi","Raurkela","Mangaluru","Tirunelveli","Malegaon","Gaya","Tiruppur","Davanagere","Kozhikode","Akola","Kurnool","Bokaro Steel City","Rajahmundry","Ballari","Agartala","Bhagalpur","Latur","Dhule","Korba","Bhilwara","Brahmapur","Mysore","Muzaffarpur","Ahmednagar","Kollam","Raghunathganj","Bilaspur","Shahjahanpur","Thrissur","Alwar","Kakinada","Nizamabad","Sagar","Tumkur","Hisar","Rohtak","Panipat","Darjiling","Kulti","Silchar","Ichalkaranji","Tirupati","Bathinda","Rajahmundry","Bhusawal","Korba","Sambalpur","Rewa","Unnao","Hugli-Chinsurah","Raiganj","Phusro","Adityapur","Alappuzha","Bahadurgarh","Machilipatnam","Rae Bareli","Jalpaiguri","Bharatpur","Pathankot","Hoshiarpur","Baramula","Adoni","Jind","Tonk","Tenali","Kancheepuram","Vapi","Sirsa","Navsari","Mahbubnagar","Puri","Robertson Pet","Erode","Batala","Haldwani-cum-Kathgodam","Vidisha","Saharsa","Thanesar","Chittoor","Veraval","Lakhimpur","Sitapur","Hindupur",);// get the q parameter from URL$q = $_REQUEST["city"];$hints = array();if ($q !== "") {$q = strtolower($q);$len=strlen($q);foreach($cities as $city) {if (stristr($q, substr($city, 0, $len))) {if (!in_array($city, $hints)) {$hints[] = $city;}}}}echo $hints === "" ? "no suggestion" : json_encode($hints);?>
output:
Comments
Post a Comment