I have a data.json file. I created an HTML file search to read the data.json file, but it does not work. Can I get help in creating a file that contains a search for flights that is in my Data Jenson file?
Thank you
This is my data.json file
{
"data": [
{
"City/Airport": "Aarhus",
"Country": "Denmark",
"IATA code": "AAR"
},
{
"City/Airport": "Abadan",
"Country": "Iran",
"IATA code": "ABD"
},
{
"City/Airport": "Abeche",
"Country": "Chad",
"IATA code": "AEH"
}
}
This is my HTML search form
<!DOCTYPE html>
<html>
<head>
<title>Flight Search</title>
</head>
<body>
<h1>Flight Search</h1>
<select name="from" id="from" type="search">
<option value="">Select a city</option>
<?php
$data = require('./data.json');
foreach ($data as $city) {
echo '<option value="' . $city['iataCode'] . '">' . $city['city'] . ', ' . $city['country'] . '</option>';
}
?>
</select>
<select name="to" id="to" type="search">
<option value="">Select a city</option>
<?php
$data = require('./data.json');
foreach ($data as $city) {
echo '<option value="' . $city['iataCode'] . '">' . $city['city'] . ', ' . $city['country'] . '</option>';
}
?>
</select>
<input type="submit" value="Search">
</form>
<script>
const data = require('./data.json');
const cities = [];
for (const city of data) {
cities.push({
name: city.City/Airport,
country: city.Country,
iataCode: city.IATA code
});
}
const from = document.getElementById('from');
const to = document.getElementById('to');
from.addEventListener('change', () => {
const iataCode = from.options[from.selectedIndex].value;
const city = cities.find(city => city.iataCode === iataCode);
document.getElementById('fromLabel').textContent = city.name;
});
to.addEventListener('change', () => {
const iataCode = to.options[to.selectedIndex].value;
const city = cities.find(city => city.iataCode === iataCode);
document.getElementById('toLabel').textContent = city.name;
});
</script>
</body>
</html>
I want to fix errors that do not work on my local server, thank you
2
Answers
OK, it is working now. I just want the field to include search not select. I could not modify the HVML file. enter image description here
Remove the PHP code and replace it with JavaScript to fetch and parse the JSON data.
Update the JSON structure in your data.json file to be an array of objects directly, without the "data" key.
Make sure your
data.json
file contains an array of objects without the"data"
key. Each object should have the keys"City/Airport"
,"Country"
, and"IATA code"
.