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: 

  1. Frontend
    1. HTML
    2. CSS
    3. JAVASCRIPT
    4. AJAX
  2. Backend 
    1. 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:

    
How To Create Auto Completing Input In HTML With PHP AJAX And Javascript - letsbug
Input before key input

How To Create Auto Completing Input In HTML With PHP AJAX And Javascript - letsbug



Comments

Categories

Big Data Analytics Binary Search Binary Search Tree Binary To Decimal binary tree Breadth First Search Bubble sort C Programming c++ Chemical Reaction and equation class 10 class 10th Class 9 Climate Complex Numbers computer network counting sort CSS Cyber Offenses Cyber Security Cyberstalking Data Science Data Structures Decimal To Binary Development diamond pattern Digital Marketing dust of snow Economics Economics Lesson 4 Email Validation English fire and ice Food Security in India Footprints Without feet Forest And Wildlife Resources game Geography Geography lesson 6 glassmorphism Glossary Graph HackerRank Solution hindi HTML image previewer India-Size And Location Insertion Sort Internet Network Status Interview Questions Introduction to cyber crime and cyber security IT javascript tricks json to CSV converter lesson 2 lesson 1 lesson 2 Lesson 3 Lesson 6 lesson 7 Life lines of National Economy life processes Linear Search Linked List lowest common ancestor Machine Learning MCQs median in array Merge sort min and max of two numbers Moment Money and Credit My Childhood Natural Vegetation and Wildlife NCERT Network connectivity devices Network Models Network Security No Men Are foreign Node.js operator overloading P5.js PHP Physical features of India Population Prime Numbers python Quick sort R language Rain on the roof Regular Expression Resources and development reversing array saakhi science Searching Algorithm Selection sort Social Media Marketing social science Software Engineering Software Testing Sorting Algorithm Stacks staircase pattern System Concepts Text Recognition The last Leaf time converter Time Passed From A Date Todo List App Tree Trending Technologies Understanding Economic Development username and password video player Visualization water resources Wired And Wireless LAN साखी
Show more

Popular Posts

Big Data MCQs(multiple choice questions) with answers - letsbug

Digital Marketing MCQ(Multiple Choice Questions) with Answers | part 1 | letsbug

Software Engineering MCQs questions with answers - letsbug