A datalist can be filled from JSON without the older ActiveX/XMLHttpRequest compatibility branches. Keep the endpoint focused on returning validated data.
const list = document.querySelector('#city2');
async function loadCities() {
const response = await fetch('city-list-ajaxck.php', {headers: {'Accept': 'application/json'}});
const cities = await response.json();
list.replaceChildren(...cities.map(city => new Option(city.name, city.name)));
}
document.querySelector('#loadCities').addEventListener('click', loadCities);
Use textContent, DOM constructors, or new Option() for returned values instead of concatenating untrusted strings into HTML.
require "config.php"; // Database Connection
You can read more on how to use config.php file here. echo "<input id="city" list="city1" >
<datalist id="city1" >";
Once database connection is established ,we can go for collecting the data. Here is the query
$sql="select city from city "; // Query to collect records
We will loop through the array and collect all the city list. While collecting we will format the out put and add them as option to the data list.
foreach ($dbo->query($sql) as $row) {
$city = htmlspecialchars((string) $row['city'], ENT_QUOTES, 'UTF-8');
echo "<option value=\"{$city}"></option>"; // Escape database output
}
Now we will add the closing tag of the datalist.
echo "</datalist>";
This will populate the datalist with data from a database table. The Ajax version requests the city list as JSON and adds each returned value with the DOM Option constructor. This keeps database values out of HTML string concatenation.
<input id="cityAjax" list="city2">
<datalist id="city2"></datalist>
<button type="button" id="loadCities">Add Options</button>
const list = document.querySelector('#city2');
async function loadCities() {
const response = await fetch('city-list-ajaxck.php', {
headers: {'Accept': 'application/json'}
});
if (!response.ok) throw new Error('Unable to load cities');
const cities = await response.json();
list.replaceChildren(...cities.map(city => new Option(city, city)));
}
document.querySelector('#loadCities').addEventListener('click', loadCities);
The endpoint can return the city column as JSON:
<?php
require 'config.php';
header('Content-Type: application/json; charset=UTF-8');
$stmt = $dbo->query('SELECT city FROM city ORDER BY city');
$cities = $stmt->fetchAll(PDO::FETCH_COLUMN);
echo json_encode($cities, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
?>
The live example below uses the same JSON response shape.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| Neha | 23-04-2015 |
| Your example is good but i am getting the database connectivity error as I have already changed the credentials of my localhost... | |
| juan | 03-04-2017 |
| it works both of them for me, but i can't understand the really function to the ajax one, i can't understand the use for that button "add options", may you explain me please? | |
| smo1234 | 04-04-2017 |
| The button takes the user click and then only populate the data list with options. While loading of the page data list is not available with the options. User can add the options by clicking the button. Such type of triggers are required when you want to filter the data based on users previous selection or choice. If user has selected Asia as region then you can trigger the datalist to show only cities of Asia | |
| Manjunatha | 28-07-2017 |
| Hi,Thank you for your great work i got your coding ,but i want to select multiple data by using (comma) , For Example if user wants to select many places by using comma (,) he can select multiple places ,please help me with it | |
| smo1234 | 31-07-2017 |
| It is better to use JQuery UI , Autocomplete . There is a Demo with multiple word search for autocomplete. | |
| Mark | 03-05-2018 |
| How can I populate the field names in the same manner, and when the a field name is chosen, its content is displayed on the page? | |
| smo1234 | 21-08-2018 |
| The way we have collected city names, the same way you can collect field names to connect to datalist. You can collect field names from a given table like this. You can use change or input event to trigger your back end script to populate data of the field. | |