Adding options to datalist from Mysql Table records.

Modern datalist loading with fetch()

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.

Datalist is added in HTML 5. You can learn basic of datalist in our HTML Section. We will develop a script to populate option ( or value ) of a datalist by taking data from a MySQL database table.

Sample table

Table for Datalist options
We have kept one sample table CITY with city name and country . For this tutorial we will use only city name column to populate our datalist. There are some sample records kept in the table to use in this tutorial. You can download the sql dump of the table along with the script at the end of this page.

Loading data

First we will connect to mysql database by using our config.php file.
require "config.php"; // Database Connection 
You can read more on how to use config.php file here.
We will develop the datalist first by connecting it to one text box. Note that we will not add the closing tag of datalist immediately as we will be adding the city list as option by taking the names from table.
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.
Here is the demo

Using Ajax

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.



The button loads the existing sample cities into the datalist without refreshing the page.

Displaying Matching words by using Autocomplete while entering text Datalist Basic

download Datalist Add Options  Script
Ajax Json XML


Subscribe to our YouTube Channel here



plus2net.com







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.




PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer